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/9p_io.zig | 3063 +++++++++++---------- src/Art.zig | 55 +- src/Db.zig | 68 +- src/File.zig | 637 +++-- src/Handover.zig | 6 +- src/Layer.zig | 104 +- src/Messages.zig | 36 +- src/Output.zig | 256 +- src/Pipe.zig | 16 +- src/Store.zig | 4 +- src/builtins.zig | 422 +-- src/c_heap.zig | 10 +- src/colors.zig | 208 +- src/config.zig | 192 +- src/diff.zig | 32 +- src/dump.zig | 288 +- src/edit.zig | 184 +- src/exec.zig | 78 +- src/fonts.zig | 68 +- src/fs.zig | 1190 ++++---- src/gui/gui.zig | 7384 +++++++++++++++++++++++++------------------------- src/host_io.zig | 990 +++---- src/layout.zig | 366 +-- src/locations.zig | 80 +- src/look.zig | 447 ++- src/lsp/lsp.zig | 22 +- src/macos.zig | 759 +++--- src/main.zig | 64 +- src/modal.zig | 128 +- src/mouse.zig | 260 +- src/ninep/cols.zig | 66 +- src/ninep/events.zig | 90 +- src/ninep/pane.zig | 64 +- src/ninep/tree.zig | 68 +- src/panes.zig | 22 +- src/pardes.zig | 213 +- src/replica.zig | 472 ++-- src/sam_edit.zig | 122 +- src/screen_state.zig | 336 +-- src/surface.zig | 74 +- src/syntax.zig | 295 +- src/tagline.zig | 68 +- src/terminal.zig | 885 +++--- src/tui/tui.zig | 2005 +++++++------- src/walk.zig | 160 +- 45 files changed, 11176 insertions(+), 11181 deletions(-) (limited to 'src') diff --git a/src/9p_io.zig b/src/9p_io.zig index 62c38521..b557594a 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -103,7 +103,6 @@ const Runner = if (supported) cloud9.serve.Runner(pardes.ctlfs, ninep.editor, .{ .listeners = 2, }) else void; - pub const Listener = struct { io: std.Io, /// The core that answers; `reset` puts a replacement in. @@ -1078,182 +1077,6 @@ fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { const testing = std.testing; -test "the socket name is a third prefix in the shared directory" { - var buf: [sun_path_len]u8 = undefined; - const p = socketPath(&buf, "/run/user/1000", "t9srv").?; - try testing.expectEqualStrings("/run/user/1000/pardes-9p-t9srv.sock", p); - try testing.expect(!std.mem.startsWith(u8, std.Io.Dir.path.basename(p), "pardes-detached-")); -} - -test "a name that is not one path component is no address at all" { - var buf: [sun_path_len]u8 = undefined; - try testing.expect(socketPath(&buf, "/run", "") == null); - try testing.expect(socketPath(&buf, "/run", "a/b") == null); - try testing.expect(socketPath(&buf, "/run", "a\x00b") == null); -} - -test "the startup sweep removes a dead pid's socket and leaves a live pid's, a named one and a plain file" { - if (comptime !supported) return error.SkipZigTest; - var dir_buf: [sun_path_len:0]u8 = undefined; - const base = socketDir(&dir_buf) orelse return error.SkipZigTest; - if (!ensureSocketDir(base)) return error.SkipZigTest; - var sub_buf: [sun_path_len:0]u8 = undefined; - const sub = std.fmt.bufPrintSentinel(&sub_buf, "{s}/deadsweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch return error.SkipZigTest; - if (libc.mkdir(sub, 0o700) != 0) return error.SkipZigTest; - var paths: [4][sun_path_len:0]u8 = undefined; - // No process has this pid: kill(pid, 0) answers ESRCH. - const dead = try std.fmt.bufPrintSentinel(&paths[0], "{s}/" ++ prefix ++ "2147483647.sock", .{sub}, 0); - const live = try std.fmt.bufPrintSentinel(&paths[1], "{s}/" ++ prefix ++ "{d}.sock", .{ sub, @as(u32, @intCast(std.c.getppid())) }, 0); - const named = try std.fmt.bufPrintSentinel(&paths[2], "{s}/" ++ prefix ++ "work.sock", .{sub}, 0); - const plain = try std.fmt.bufPrintSentinel(&paths[3], "{s}/" ++ prefix ++ "2147483646.sock", .{sub}, 0); - defer { - for ([_][:0]const u8{ dead, live, named, plain }) |p| _ = libc.unlink(p); - _ = libc.rmdir(sub); - } - for ([_][:0]const u8{ dead, live, named }) |p| { - const fd = bindSocket(p); - if (fd < 0) return error.SkipZigTest; - _ = libc.close(fd); // closed: what a killed editor leaves - } - const fd = libc.open(plain, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); - if (fd < 0) return error.SkipZigTest; - _ = libc.close(fd); - sweepDeadSockets(testing.io, sub); - try testing.expect(statNoFollow(dead) == null); - try testing.expect(statNoFollow(live) != null); - try testing.expect(statNoFollow(named) != null); - try testing.expect(statNoFollow(plain) != null); -} - -test "the registry sweep takes the dead entries and leaves everything else" { - if (comptime !supported) return error.SkipZigTest; - // Under the real runtime directory, because a sun_path is 108 bytes - // and the test cache's temporary directories are longer than that. - var dir_buf: [sun_path_len:0]u8 = undefined; - const base = socketDir(&dir_buf) orelse return error.SkipZigTest; - if (!ensureSocketDir(base)) return error.SkipZigTest; - - var svc_buf: [sun_path_len:0]u8 = undefined; - const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/sweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch - return error.SkipZigTest; - if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest; - - // The sockets live where the real ones do -- beside the registry, not in - // it, and named the way a session names them -- because the sweep only - // follows an entry to a target of exactly that shape and place. - var paths: [6][sun_path_len:0]u8 = undefined; - const pid: u32 = @intCast(libc.getpid()); - const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/pardes-9p-sweeplive-{d}.sock", .{ base, pid }, 0); - const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/pardes-9p-sweepdead-{d}.sock", .{ base, pid }, 0); - const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0); - const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0); - const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0); - // A dead entry pointing at something that is NOT one of our sockets: the - // entry goes, the file it named must not. - const outsider_sock = try std.fmt.bufPrintSentinel(&paths[5], "{s}/sweep-outsider-{d}.sock", .{ base, pid }, 0); - var outsider_buf: [sun_path_len:0]u8 = undefined; - const outsider = try std.fmt.bufPrintSentinel(&outsider_buf, "{s}/outsider", .{svc}, 0); - // Live, its lock held, but bound and not listening: a connect is - // refused, on every system, as FreeBSD refuses one to a live session - // whose queue is full. Its lock is what says it lives. - var starting_paths: [2][sun_path_len:0]u8 = undefined; - const starting_sock = try std.fmt.bufPrintSentinel(&starting_paths[0], "{s}/pardes-9p-sweepstarting-{d}.sock", .{ base, pid }, 0); - const starting = try std.fmt.bufPrintSentinel(&starting_paths[1], "{s}/starting", .{svc}, 0); - var locks: [3][lock_path_len:0]u8 = undefined; - const dead_lock = lockPath(&locks[2], dead_sock).?; - defer { - for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger, outsider_sock, outsider, starting_sock, starting, dead_lock }) |p| _ = libc.unlink(p); - _ = libc.rmdir(svc); - } - - const live_lock = claim(live_sock, &locks[0]) orelse return error.LockFailed; - defer release(live_lock, std.mem.sliceTo(&locks[0], 0)); - const listening = bindSocket(live_sock); - try testing.expect(listening >= 0); - defer _ = libc.close(listening); - try testing.expectEqual(@as(c_int, 0), libc.listen(listening, 1)); - - const starting_lock = claim(starting_sock, &locks[1]) orelse return error.LockFailed; - defer release(starting_lock, std.mem.sliceTo(&locks[1], 0)); - const bound = bindSocket(starting_sock); - try testing.expect(bound >= 0); - defer _ = libc.close(bound); - try testing.expectEqual(@as(c_int, 0), libc.symlink(starting_sock, starting)); - - // Bound and then dropped, its lock let go: the files stay, and nobody - // answers it -- exactly what a killed session leaves behind. - const abandoned = bindSocket(dead_sock); - try testing.expect(abandoned >= 0); - _ = libc.close(abandoned); - const dropped = libc.open(dead_lock, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); - try testing.expect(dropped >= 0); - try testing.expectEqual(@as(c_int, 0), libc.flock(dropped, std.posix.LOCK.EX)); - _ = libc.close(dropped); - - try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live)); - try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead)); - // Dead too, but its target is not one of our sockets by name, so the - // entry must go and the file it named must survive untouched. - const outside = bindSocket(outsider_sock); - try testing.expect(outside >= 0); - defer _ = libc.close(outside); - try testing.expectEqual(@as(c_int, 0), libc.symlink(outsider_sock, outsider)); - // Not a symlink, so not this program's to reason about, even though - // connecting to it is refused exactly like the dead socket. - try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" }); - - try testing.expectEqual(Probe.live, probe(live)); - try testing.expectEqual(Probe.stale, probe(dead)); - - sweepRegistry(testing.io, svc, base); - - try testing.expect(statNoFollow(dead) == null); - try testing.expect(statNoFollow(dead_sock) == null); - try testing.expect(statNoFollow(dead_lock) == null); - try testing.expect(statNoFollow(starting) != null); - try testing.expect(statNoFollow(starting_sock) != null); - try testing.expect(statNoFollow(live) != null); - try testing.expect(statNoFollow(live_sock) != null); - try testing.expect(statNoFollow(stranger) != null); - try testing.expect(statNoFollow(outsider) == null); - try testing.expect(statNoFollow(outsider_sock) != null); - try testing.expectEqual(Probe.live, probe(live)); -} - -fn bindSocket(path: [:0]const u8) c_int { - const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); - if (fd < 0) return fd; - var addr: libc.sockaddr.un = .{ .path = @splat(0) }; - @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); - if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { - _ = libc.close(fd); - return -1; - } - return fd; -} - -test "TCP addresses are numeric and normalize mapped IPv4" { - const loopback = try networkAddress("tcp!127.0.0.1!5640", false); - try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:127.0.0.1!5640", false)); - try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:7f00:1!5640", false)); - try testing.expectEqualDeep(try networkAddress("tcp!::1!5640", false), try networkAddress("tcp!0:0:0:0:0:0:0:1!5640", false)); - try testing.expectEqual(@as(u16, 0), (try networkAddress("tcp!127.0.0.1!0", true)).getPort()); - for ([_][]const u8{ "tcp!localhost!5640", "tcp!127.0.0.1!0", "tcp!127.0.0.1!-1", "tcp!127.0.0.1!65536", "tcp!127.0.0.1!", "tcp!!5640" }) |dial| - try testing.expectError(error.BadDial, networkAddress(dial, false)); - try Client.validateDial("tcp!127.0.0.1!5640"); - try Client.validateDial("/tmp/pardes-owned.sock"); - try Client.validateDial("unix!/tmp/pardes-owned.sock"); - try testing.expectError(error.BadDial, Client.validateDial("unix!work")); - try testing.expectError(error.BadDial, Client.validateDial("nowhere!x")); - try Client.validateDial("/tmp/odd!name.sock"); - try testing.expectError(error.BadDial, Client.validateDial("rel/dir.sock")); - try testing.expectError(error.BadDial, Client.validateDial("unix!")); - try testing.expectError(error.BadDial, Client.validateDial("unix!/tmp/a\x00b")); - try testing.expectError(error.BadDial, Client.validateDial("tcp!localhost!5640")); - try testing.expectError(error.BadDial, Client.validateDial("/tmp/a\x00b")); - try testing.expectError(error.BadDial, Client.validateDial("quic!127.0.0.1!5640")); -} - extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; /// A test's own runtime directory under /tmp, which XDG_RUNTIME_DIR names @@ -1279,1512 +1102,1688 @@ const TempRuntime = struct { } }; -test "a runtime directory that makes the socket's path pass sun_path is refused in words, the editor running on" { - if (comptime !supported) return error.SkipZigTest; - const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - var rt: TempRuntime = .{}; - try rt.init("words"); - defer rt.deinit(); - var buf: [256]u8 = undefined; - try testing.expect(noSocket("x", &buf) == null); - // A directory of 91 bytes (the ledger's was 83, a pid's digits from the - // edge): with a 1-byte name and a pid the socket's path passes sun_path. - var long_buf: [128:0]u8 = undefined; - const long = try std.fmt.bufPrintSentinel(&long_buf, "{s}/{s}", .{ std.mem.sliceTo(&rt.directory, 0), &@as([66]u8, @splat('d')) }, 0); - try testing.expectEqual(@as(usize, 91), long.len); - try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", long, 1)); - const words = noSocket("x", &buf) orelse return error.NotRefused; - try testing.expect(std.mem.startsWith(u8, words, "9p: the socket path is ")); - try testing.expect(std.mem.endsWith(u8, words, " bytes, 108 is the most: set XDG_RUNTIME_DIR shorter")); - // The session's own words, where its pane shows them; no listener. - try testing.expect(start(testing.io, testing.allocator, p) == null); - const pane = p.panes[0].?; - try testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "9p: the socket path is ")); -} - -test "a runtime directory open to others is refused in words, never a silent session with no socket" { - if (comptime !supported) return error.SkipZigTest; - const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - var rt: TempRuntime = .{}; - try rt.init("open"); - defer rt.deinit(); - // `mkdir -m 700 -p dir/sub` leaves dir itself at the umask's 755. - try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o755)); - var buf: [256]u8 = undefined; - const words = noSocket("x", &buf) orelse return error.NotRefused; - try testing.expect(std.mem.indexOf(u8, words, "must be a directory of yours alone (mode 755") != null); - try testing.expect(start(testing.io, testing.allocator, p) == null); - const pane = p.panes[0].?; - try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "chmod 700 it") != null); - try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o700)); - try testing.expect(noSocket("x", &buf) == null); -} +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; -test "a socket path too long for sun_path is no listener, and leaves the editor's turn as it was" { - if (comptime !supported) return error.SkipZigTest; - const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - var rt: TempRuntime = .{}; - try rt.init("long"); - defer rt.deinit(); - // A name that fits: the directory is one a listener takes. - var fits: [sun_path_len]u8 = undefined; - try testing.expect(socketPath(&fits, std.mem.sliceTo(&rt.directory, 0), "short") != null); - const long = &@as([120]u8, @splat('n')); - try testing.expectError(error.NameTooLong, listen(testing.io, testing.allocator, p, long, "", null)); - try testing.expect(pardes.turn.answer_held == null); - try testing.expect(pardes.turn.wake_parked == null); - try testing.expect(pardes.turn.io == null); +pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listener { + var name: [16]u8 = undefined; + // unreachable: a u32 is at most 10 digits + const fallback = std.fmt.bufPrint(&name, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable; + return listen(io, gpa, core, core.opts.ninep_name, fallback, core.opts.ninep_tcp) catch { + if (refusal.len > 0) core.setMessage(0, refusal) else core.reportError(0, "9p listener", error.ListenFailed); + return null; + }; } -test "a listening editor posts itself into the 9P registry and unposts on stop" { - if (comptime !supported) return error.SkipZigTest; - const gpa = testing.allocator; - var rt: TempRuntime = .{}; - try rt.init("post"); - defer rt.deinit(); - const dir = std.mem.sliceTo(&rt.directory, 0); - - var entry_buf: [sun_path_len:0]u8 = undefined; - const entry = try std.fmt.bufPrintSentinel(&entry_buf, "{s}/9p/pardes/unit", .{dir}, 0); - var sock_buf: [sun_path_len:0]u8 = undefined; - const sock = try std.fmt.bufPrintSentinel(&sock_buf, "{s}/" ++ prefix ++ "unit.sock", .{dir}, 0); - - var link: [sun_path_len]u8 = undefined; - { - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - const l = try listen(testing.io, gpa, p, "unit", "", null); - defer l.deinit(gpa); - // The socket stays exactly where pardes has always bound it: - // adopting the registry moves nothing, it only advertises. - try testing.expect(statNoFollow(sock) != null); - // It appeared already listening, renamed into place from a name of - // its own, which is gone; its lock held all the while. - try testing.expect(transport.isListening(sock)); - try testing.expectEqual(Probe.live, lockState(sock)); - var tmp_buf: [sun_path_len:0]u8 = undefined; - try testing.expect(statNoFollow(try std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ sock, libc.getpid() }, 0)) == null); - // And the registry holds a symlink to it one directory down, so - // several editors group under /mnt/9p/pardes/ instead of - // crowding the registry root — the layout zmx posts its - // sessions in. - const n = libc.readlink(entry, &link, link.len); - try testing.expect(n > 0); - try testing.expectEqualStrings(sock, link[0..@intCast(n)]); - // A host path no fid names is swept, but never while a request is - // out in a syscall: it may be that request's, mid-walk. - try p.fs.os_paths.append(gpa, .{ .node = @import("fs.zig").os_node | 1, .path = try gpa.dupe(u8, "/tmp") }); - pardes.turn.out = 1; - l.collectOs(); - pardes.turn.out = 0; - try testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); - l.collectOs(); - try testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); +/// What a pane shell is told about the editor above it, set into this +/// process's environment just before `forkpty` so the child inherits it. +/// +/// Two independent facts, and they are separate variables because they answer +/// separate questions. `PARDES_PID` says "you are inside this editor, and it +/// will take a Look from you": a session whose 9P listener never came up still +/// owns its children, so the child says so rather than looking, from its own +/// side, exactly like no pardes at all. `PARDES_9P` and `PARDES_PANE` say how +/// to reach it, and a `--nested` session exports them too — its socket stays +/// open to scripts and to mounted shells — while withholding `PARDES_PID`, +/// which is the whole of what `--nested` means. +/// +/// The socket is this process's own (`listen` keeps it, its listener's +/// path, until `deinit`), for a pane's shell and for a command run off the +/// loop (an Edit's filter) alike. Told to children through +/// host_io.ChildEnv, never set into this process's own environment (see +/// ChildEnv.exportVar for why). +pub fn exportEnv(serial: u32, adopts: bool) void { + const socket: ?[]const u8 = if (own_socket_len > 0) own_socket[0..own_socket_len] else null; + const ChildEnv = @import("host_io.zig").ChildEnv; + var pid_buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable else null); // a u32 fits 16 + if (socket) |own| { + var buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_9P", own); + exportMount(own); + ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); + return; } - // Stopping takes the name back out, so the next editor of that name - // is not refused by its own corpse; the lock goes with the socket. - try testing.expect(libc.readlink(entry, &link, link.len) < 0); - try testing.expectEqual(Probe.none, lockState(sock)); + ChildEnv.exportVar("PARDES_9P", null); + ChildEnv.exportVar("PARDES_PANE", null); + ChildEnv.exportVar("PARDES_MOUNT", null); } -test "Unix and TCP share one listener through reads writes reconnects and reset" { - if (comptime !supported) return error.SkipZigTest; - const gpa = testing.allocator; - var rt: TempRuntime = .{}; - try rt.init("tcp"); - defer rt.deinit(); - const replacement = try gpa.alloc(u8, 3 * msize + 27); - defer gpa.free(replacement); - @memset(replacement, 'x'); - @memcpy(replacement[0.."changed café λ\n".len], "changed café λ\n"); - replacement[replacement.len - 1] = '\n'; +/// $PARDES_MOUNT, the session's own directory, when the environment says +/// where it is -- never by looking at the mount, which this editor serves +/// (the self-mount deadlock). Under `9ns --mntgen` (NINE_MNTGEN=1) it is +/// `$NINE_MOUNT/pardes/`, the name the registry gives the socket. +/// Any other $NINE_MOUNT is a mount of another server, made before this +/// session had a socket: unknown, so unset, and a script falls back to +/// `9p -a "unix!$PARDES_9P"`. +fn exportMount(sock_path: []const u8) void { + const mntgen = if (libc.getenv("NINE_MNTGEN")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; + const root = if (libc.getenv("NINE_MOUNT")) |v| std.mem.span(v) else ""; + const base = std.Io.Dir.path.basename(sock_path); + const sock_prefix = "pardes-9p-"; + const suffix = ".sock"; + if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { + var buf: [4096]u8 = undefined; + if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { + return @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", mount); + } else |_| {} + } + @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null); +} - const Worker = struct { - dial: []const u8, - body_path: []const u8, - expected: []const u8, - replacement: []const u8, - done: std.atomic.Value(bool) = .init(false), - failure: ?anyerror = null, +pub const Client = struct { + pub const budget_ms: i64 = 2000; + /// Each write of a long one has this long to be answered (transact). + pub const write_budget_ms: i64 = 30_000; - fn run(w: *@This()) void { - defer w.done.store(true, .release); - w.check() catch |err| { - w.failure = err; - }; - } + pub const max_depth: usize = 2 * ninep.max_welem; - fn check(w: *@This()) !void { - const before = try Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len); - defer testing.allocator.free(before); - try testing.expectEqualStrings(w.expected, before); - try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len - 1)); - const listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", 128); - defer testing.allocator.free(listing); - const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len); - defer testing.allocator.free(exact_listing); - try testing.expectEqualStrings(listing, exact_listing); - try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len - 1)); - try Client.write(testing.allocator, w.dial, w.body_path, w.replacement); - const after = try Client.read(testing.allocator, w.dial, w.body_path, w.body_path); - defer testing.allocator.free(after); - try testing.expectEqualStrings(w.replacement, after); - const screen = try Client.read(testing.allocator, w.dial, "/screen", "/screen"); - defer testing.allocator.free(screen); - const parsed = try std.json.parseFromSlice(struct { cols: u16, rows: u16 }, testing.allocator, screen, .{ .ignore_unknown_fields = true }); - defer parsed.deinit(); - try testing.expectEqual(@as(u16, 40), parsed.value.cols); - try testing.expectEqual(@as(u16, 12), parsed.value.rows); - } + const uname = "pardes"; + + const Dial = union(enum) { unix: [:0]const u8, tcp: std.Io.net.IpAddress }; + + pub const Error = error{ + PathTooDeep, + BadDial, + Dial, + Hangup, + Timeout, + Botch, + Remote, + IsDirectory, + NotFound, + FileTooLarge, }; - for ([_][]const u8{ "127.0.0.1", "::1" }) |host| { - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - const pane = try p.setTestFile("initial\n"); - while (p.nextEffect()) |_| {} - var bind_buf: [64]u8 = undefined; - const bind = try std.fmt.bufPrint(&bind_buf, "tcp!{s}!0", .{host}); - const l = try listen(testing.io, gpa, p, "roundtrip", "", bind); - defer { - l.reset(p); - l.deinit(gpa); - } - try testing.expect(l.path().len != 0); - try testing.expectEqual(@as(usize, max_conns), l.runner.conns.len); - const port = l.tcp_address.?.getPort(); - try testing.expect(port != 0); - var dial_buf: [64]u8 = undefined; - const network_dial = try std.fmt.bufPrint(&dial_buf, "tcp!{s}!{d}", .{ host, port }); - var body_buf: [64]u8 = undefined; - const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); - for ([_][]const u8{ network_dial, l.path(), network_dial }, 0..) |dial, attempt| { - var worker: Worker = .{ .dial = dial, .body_path = body, .expected = if (attempt == 0) "initial\n" else replacement, .replacement = replacement }; - const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); - defer thread.join(); - // The editor rests while the client works: its requests are - // answered on the runner's tasks, not by this thread. - const deadline = nowMs() + 3 * Client.budget_ms; - pardes.turn.rest(); - while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); - // The client has hung up, but its connection's task may not have - // seen that yet. The releases it then owes are refused once - // `reset` starts cutting (they name the old editor's opens), and - // this test's "replacement" is the same editor, so they would - // stay in `p.fs.opens`. Let the hangup pay them first, resting - // so the task can take the turn: that is what is under test here. - const settle_by = nowMs() + 3 * Client.budget_ms; - while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); - pardes.turn.wake(); - try testing.expect(worker.done.load(.acquire)); - if (worker.failure) |err| return err; - try testing.expectEqual(@as(usize, 0), l.runner.count()); - l.reset(p); - try testing.expectEqual(@as(usize, 0), l.runner.count()); - for (p.fs.opens) |o| try testing.expect(o.node == 0); - } + pub fn read(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8) ![]u8 { + return readLimit(gpa, dial, path, display_path, limits.max_file_bytes); } -} -test "a change waits while the editor is out mid-step, a read does not, and the change lands when the editor rests" { - if (comptime !supported) return error.SkipZigTest; - const gpa = testing.allocator; - var rt: TempRuntime = .{}; - try rt.init("park"); - defer rt.deinit(); + pub fn readLimit(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { + return fetch(false, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); + } - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - const pane = try p.setTestFile("before\n"); - while (p.nextEffect()) |_| {} - // This thread is the editor's: it has the turn from here on. - const l = try listen(testing.io, gpa, p, "park", "", null); - defer { - l.reset(p); - l.deinit(gpa); + /// readLimit through a mount: its connection kept for the next (`kept`). + pub fn readMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { + return fetch(true, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); } - var body_buf: [64]u8 = undefined; - const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); - const Writer = struct { - dial: []const u8, - path: []const u8, - done: std.atomic.Value(bool) = .init(false), - failure: ?anyerror = null, - fn run(w: *@This()) void { - defer w.done.store(true, .release); - Client.write(testing.allocator, w.dial, w.path, "after\n") catch |err| { - w.failure = err; - }; - } - }; - var writer: Writer = .{ .dial = l.path(), .path = body }; + /// One operation on `path`, a read of up to `read_limit` or a write of + /// `write_bytes`, on the connection kept for `dial` when `keep`: the + /// peer's words, when it refuses, kept for lastSaid. + fn fetch(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, write_bytes: ?[]const u8, read_limit: usize) ![]u8 { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + return fetchBytes(gpa, dial, names[0..n], &remote, write_bytes, display_path, read_limit, keep) catch |err| { + if (err == error.Remote) said = remote; + return err; + }; + } - // The editor goes out mid-step -- a Look resolving a path, say -- and a - // write arrives meanwhile. It must not land: the step still holds - // pointers into the pane. A read is answered all the same. - pardes.turn.yield(); - const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer}); - defer thread.join(); - nap(150); - try testing.expect(!writer.done.load(.acquire)); - const seen = try Client.readLimit(gpa, l.path(), body, body, 64); - defer gpa.free(seen); - try testing.expectEqualStrings("before\n", seen); - try testing.expect(!writer.done.load(.acquire)); - pardes.turn.back(); - try testing.expectEqualStrings("before\n", pane.file.?.content); + /// The peer's own words for the last error.Remote a read or write here + /// got (its Rerror), for a caller that says why: this thread's, as the + /// editor's mounts and a Handover job each ask from their own. + threadlocal var said: RemoteError = .{}; + pub fn lastSaid() []const u8 { + return said.buf[0..said.len]; + } - // Resting is what lets it in: the parked write is retried, served, and - // the client hears back. - pardes.turn.rest(); - const deadline = nowMs() + Client.budget_ms; - while (!writer.done.load(.acquire) and nowMs() < deadline) nap(1); - pardes.turn.wake(); - try testing.expect(writer.done.load(.acquire)); - if (writer.failure) |err| return err; - // Its bytes are held until its open is let go (pane.zig `batchFor`), and - // the client lets it go without waiting: rested again until that lands, - // the body read only while the editor has the turn. - while (!std.mem.eql(u8, pane.file.?.content, "after\n") and nowMs() < deadline) { - pardes.turn.rest(); - nap(1); - pardes.turn.wake(); + /// Whether a peer answers at `dial`: a version and attach, and its root + /// read. Any answer from the peer, an error of its own included, is one. + pub fn probe(gpa: std.mem.Allocator, dial: []const u8) !void { + return probeWith(false, gpa, dial); } - try testing.expectEqualStrings("after\n", pane.file.?.content); -} -test "a mount's connection is kept between operations, and one the peer hung up is dialled again" { - if (comptime !supported) return error.SkipZigTest; - const gpa = testing.allocator; - var rt: TempRuntime = .{}; - try rt.init("kept"); - defer rt.deinit(); + /// probe for a Mount: the connection kept as the mount's. + pub fn probeMount(gpa: std.mem.Allocator, dial: []const u8) !void { + return probeWith(true, gpa, dial); + } - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - const pane = try p.setTestFile("before\n"); - while (p.nextEffect()) |_| {} - const l = try listen(testing.io, gpa, p, "kept", "", null); - defer { - l.reset(p); - l.deinit(gpa); + fn probeWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8) !void { + const got = fetch(keep, gpa, dial, "", "", null, 0) catch |err| switch (err) { + error.IsDirectory, error.NotFound, error.Remote, error.FileTooLarge => return, + else => return err, + }; + gpa.free(got); } - var body_buf: [64]u8 = undefined; - const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); - const long = try gpa.alloc(u8, 2 * msize + 5); - defer gpa.free(long); - @memset(long, 'k'); - long[long.len - 1] = '\n'; - const Worker = struct { - l: *Listener, - body: []const u8, - long: []const u8, - done: std.atomic.Value(bool) = .init(false), - failure: ?anyerror = null, - fn run(w: *@This()) void { - defer w.done.store(true, .release); - w.check() catch |err| { - w.failure = err; - }; - } - fn read(w: *@This(), want: []const u8) !void { - const got = try Client.readMount(testing.allocator, w.l.path(), w.body, w.body, limits.max_file_bytes); - defer testing.allocator.free(got); - try testing.expectEqualStrings(want, got); + pub fn write(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { + gpa.free(try fetch(false, gpa, dial, path, path, bytes, limits.max_file_bytes)); + } + + /// write through a mount: its connection kept for the next (`kept`). + pub fn writeMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { + gpa.free(try fetch(true, gpa, dial, path, path, bytes, limits.max_file_bytes)); + } + + const RemoteError = struct { + buf: [ninep.errmax]u8 = undefined, + len: usize = 0, + + fn set(r: *RemoteError, msg: []const u8) error{Remote} { + r.keep(msg); + return error.Remote; } - fn check(w: *@This()) !void { - defer Client.forget(w.l.path()); - try w.read("before\n"); - try w.read("before\n"); - // A write longer than a message, and a miss, on the same one. - try Client.writeMount(testing.allocator, w.l.path(), w.body, w.long); - try w.read(w.long); - try testing.expectError(error.NotFound, Client.readMount(testing.allocator, w.l.path(), "/pane/no-such", "/pane/no-such", 64)); - try testing.expectEqual(@as(u64, 1), w.l.accepts.load(.acquire)); - // The peer hangs up (a Restore cuts its clients): the next - // operation dials again and is answered. - for (&w.l.runner.conns) |*conn| if (conn.live()) conn.close(); - const by = nowMs() + Client.budget_ms; - while (w.l.runner.count() != 0 and nowMs() < by) nap(1); - try w.read(w.long); - try testing.expectEqual(@as(u64, 2), w.l.accepts.load(.acquire)); + + fn keep(r: *RemoteError, msg: []const u8) void { + r.len = @min(msg.len, r.buf.len); + @memcpy(r.buf[0..r.len], msg[0..r.len]); } }; - var worker: Worker = .{ .l = l, .body = body, .long = long }; - pardes.turn.rest(); - const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); - const deadline = nowMs() + 3 * Client.budget_ms; - while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); - thread.join(); - // Forgotten: the kept connection is closed, and its task sees it. - const settle_by = nowMs() + Client.budget_ms; - while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); - pardes.turn.wake(); - if (worker.failure) |err| return err; - try testing.expectEqual(@as(usize, 0), l.runner.count()); -} - -test "a connection holds up to 128 reads, and the next is refused in words" { - try testing.expectEqual(@as(usize, 128), ninep.max_held); - if (comptime supported) try testing.expectEqualStrings("too many reads waiting: 128", Runner.Engine.e_waiting); -} -test "a held read is answered when the log has news, and a flushed one spends nothing" { - if (comptime !supported) return error.SkipZigTest; - const gpa = testing.allocator; - var rt: TempRuntime = .{}; - try rt.init("held"); - defer rt.deinit(); + fn elements(path: []const u8, out: *[max_depth][]const u8) Error!usize { + var n: usize = 0; + var it = std.mem.tokenizeScalar(u8, path, '/'); + while (it.next()) |name| { + if (n == out.len) return Error.PathTooDeep; + out[n] = name; + n += 1; + } + return n; + } - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - _ = try p.setTestFile("held\n"); - p.update(.tick); // the pane is logged, before the log is opened - while (p.nextEffect()) |_| {} - const l = try listen(testing.io, gpa, p, "held", "", null); - defer { - l.reset(p); - l.deinit(gpa); + fn resolve(buf: *[sun_path_len]u8, dial: []const u8) error{BadDial}!Dial { + if (dial.len == 0) return error.BadDial; + if (std.mem.startsWith(u8, dial, "tcp!")) return .{ .tcp = try networkAddress(dial, false) }; + const explicit_unix = std.mem.startsWith(u8, dial, "unix!"); + // A network this does not dial (`nowhere!x`) is a malformed address, + // not a session named so. + if (!explicit_unix and std.mem.indexOfScalar(u8, dial, '/') == null and std.mem.indexOfScalar(u8, dial, '!') != null) return error.BadDial; + const path = if (explicit_unix) dial[5..] else dial; + if (explicit_unix and !std.mem.startsWith(u8, path, "/")) return error.BadDial; + if (std.mem.indexOfScalar(u8, path, '/') != null) { + // A socket's path is absolute: a relative one would mean wherever + // the editor happens to run. + if (path[0] != '/') return error.BadDial; + if (std.mem.indexOfScalar(u8, path, 0) != null) return error.BadDial; + return .{ .unix = std.fmt.bufPrintSentinel(buf, "{s}", .{path}, 0) catch return error.BadDial }; + } + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return error.BadDial; + return .{ .unix = socketPath(buf, dir, dial) orelse return error.BadDial }; } - // This thread is the editor's and plays the client too, resting while - // it does so that the runner's tasks can take the turn and answer. - const s = try gpa.create(Client.Session); - defer gpa.destroy(s); - s.* = .{ .fd = -1, .deadline = nowMs() + 3 * Client.budget_ms, .display_path = "/log" }; - var sock_buf: [sun_path_len]u8 = undefined; - pardes.turn.rest(); - defer pardes.turn.wake(); - s.fd = try Client.connect(try Client.resolve(&sock_buf, l.path()), s.deadline); - defer _ = libc.close(s.fd); - s.cl = .init(.{ .in = &s.in, .out = &s.out }); - var remote: Client.RemoteError = .{}; - _ = try s.ask(.{ .version = .{} }, &remote); - _ = try s.ask(.{ .attach = .{ .fid = 0, .uname = "held" } }, &remote); - _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"log"} } }, &remote); - _ = try s.ask(.{ .open = .{ .fid = 1, .mode = ninep.ordwr } }, &remote); - var frozen: u64 = 0; - while (true) { - const n = (try s.ask(.{ .read = .{ .fid = 1, .offset = frozen, .count = 4096 } }, &remote)).read.len; - if (n == 0) break; - frozen += n; + + pub fn validateDial(dial: []const u8) error{BadDial}!void { + var buf: [sun_path_len]u8 = undefined; + _ = try resolve(&buf, dial); } - _ = try s.ask(.{ .write = .{ .fid = 1, .offset = 0, .data = "follow\n" } }, &remote); - const heldNow = struct { - /// Waits until the core holds `n` reads. - fn count(core: *pardes.Pardes, n: usize) !void { - const deadline = nowMs() + Client.budget_ms; - while (nowMs() < deadline) { - pardes.turn.wake(); - var got: usize = 0; - for (core.fs.opens) |o| got += @intFromBool(o.held != null); - pardes.turn.rest(); - if (got == n) return; - nap(1); - } - return error.Timeout; + const Session = struct { + fd: c_int, + deadline: i64, + display_path: []const u8, + cl: ninep.Client = undefined, + in: [msize]u8 = undefined, + out: [msize]u8 = undefined, + stage: [msize]u8 = undefined, + /// Version and attach answered: fid 0 is the peer's root, and each + /// operation walks a fid of its own from it, so a kept connection + /// (`kept`) pays for neither again. + attached: bool = false, + root_qid: ninep.Qid = undefined, + next_fid: u32 = 1, + /// Tags whose answers nobody waits for (a clunk's): dropped by + /// whoever settles next. + unwaited: u32 = 0, + /// The dial a kept connection answers for. + dial_buf: [sun_path_len + 32]u8 = undefined, + dial_len: usize = 0, + + fn wait(s: *Session, events: i16) Error!void { + if (s.deadline - nowMs() <= 0) return Error.Timeout; + return transport.wait(s.fd, events, s.deadline) catch |err| switch (err) { + error.Timeout => Error.Timeout, + else => Error.Hangup, + }; } - }; - const serial = p.panes[0].?.serial; - var event_path: [32]u8 = undefined; - var event_names: [3][]const u8 = .{ "pane", try std.fmt.bufPrint(&event_path, "{d}", .{serial}), "event" }; - _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 2, .names = &event_names } }, &remote); - _ = try s.ask(.{ .open = .{ .fid = 2, .mode = ninep.oread } }, &remote); - // Flushed while held, a read is gone from the engine without the core - // hearing of it. Its tag, asked again at once for a read of the pane's - // event, must not be answered with the log's next record, and that - // record must reach the log's next read. - const flushed = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); - try s.flush(); - try heldNow.count(p, 1); - _ = try s.cl.submit(.{ .flush = .{ .oldtag = flushed } }); - const interrupted = try s.settle(); - try testing.expectEqual(flushed, interrupted.tag); - try testing.expect(interrupted.result == .fail); - try testing.expect((try s.settle()).result == .flush); - const reused = try s.cl.submit(.{ .read = .{ .fid = 2, .offset = 0, .count = 4096 } }); - try testing.expectEqual(flushed, reused); - try s.flush(); - try heldNow.count(p, 2); - pardes.turn.wake(); - p.setMessage(0, "after the flush"); - pardes.turn.rest(); - try heldNow.count(p, 1); - pardes.turn.wake(); - p.fs.origin = 'K'; - pardes.ctlfs.events.noteAction(p, 0, .body_exec, 0, 4, 0, "held"); - pardes.turn.rest(); - const clicked = try s.settle(); - try testing.expectEqual(reused, clicked.tag); - try testing.expectEqualStrings("KX0 4 0 4 held\n", clicked.result.read); - try testing.expect(std.mem.indexOf(u8, (try s.ask(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }, &remote)).read, "after the flush") != null); + fn flush(s: *Session) Error!void { + while (s.cl.output().len != 0) { + if (nowMs() >= s.deadline) return Error.Timeout; + const bytes = s.cl.output(); + try s.wait(poll_out); + const sent = (transport.write(s.fd, bytes) catch return Error.Hangup) orelse continue; + s.cl.wrote(@intCast(sent)); + } + } - // Held, a read is answered by the record that arrives, on its own - // connection, with no retry of every parked request asked for; a - // second read on the same open meanwhile is refused, not orphaned. - const waiting = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); - try s.flush(); - try heldNow.count(p, 1); - const second = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); - const refused = try s.settle(); - try testing.expectEqual(second, refused.tag); - try testing.expectEqualStrings(pardes.ctlfs.e_in_use, refused.result.fail); - pardes.turn.wake(); - p.setMessage(0, "while held"); - const retry_all = pardes.turn.parked; - pardes.turn.rest(); - try testing.expect(!retry_all); - const answered = try s.settle(); - try testing.expectEqual(waiting, answered.tag); - try testing.expect(std.mem.indexOf(u8, answered.result.read, "while held") != null); + fn settle(s: *Session) Error!ninep.Client.Done { + while (true) { + if (nowMs() >= s.deadline) return Error.Timeout; + try s.flush(); + if (s.cl.take()) |done| { + if (done.tag < 32 and s.unwaited & bit(done.tag) != 0) { + s.unwaited &= ~bit(done.tag); + continue; + } + return done; + } + if (s.cl.dead) return Error.Botch; + const room = s.cl.in.len - s.cl.in_len; + if (room == 0) return Error.Botch; + try s.wait(poll_in); + const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return Error.Hangup) orelse continue; + if (got == 0) return Error.Hangup; + const n = s.cl.push(s.stage[0..@intCast(got)]); + std.debug.assert(n == @as(usize, @intCast(got))); + } + } - // Clunked, the log's held read is interrupted by the engine and the - // record it would have had is spent on nobody. - _ = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); - try s.flush(); - try heldNow.count(p, 1); - s.drop(1); - s.drop(2); - try heldNow.count(p, 0); + fn ask(s: *Session, req: ninep.Client.Request, remote: *RemoteError) Error!ninep.Client.Result { + _ = s.cl.submit(req) catch return Error.Botch; + const done = try s.settle(); + if (done.result == .fail) return remote.set(done.result.fail); + if (std.mem.eql(u8, @tagName(done.result), @tagName(std.meta.activeTag(req)))) return done.result; + return Error.Botch; + } - // Records queued as a Restore comes reach a follower in the answer to - // the read it holds, all of them, before the hangup cuts it. (The - // interrupted read above answered first: one clunk's answer is unread.) - _ = try s.settle(); - _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 3, .names = &.{"log"} } }, &remote); - _ = try s.ask(.{ .open = .{ .fid = 3, .mode = ninep.ordwr } }, &remote); - _ = try s.ask(.{ .write = .{ .fid = 3, .offset = 0, .data = "follow new\n" } }, &remote); - const last = try s.cl.submit(.{ .read = .{ .fid = 3, .offset = 0, .count = 4096 } }); - try s.flush(); - try heldNow.count(p, 1); - pardes.turn.wake(); - p.setMessage(0, "queued one"); - p.setMessage(0, "queued two"); - p.setMessage(0, "queued three"); - l.reset(p); - pardes.turn.rest(); - const cut = try s.settle(); - try testing.expectEqual(last, cut.tag); - for ([_][]const u8{ "queued one", "queued two", "queued three" }) |said| - try testing.expect(std.mem.indexOf(u8, cut.result.read, said) != null); -} + fn drop(s: *Session, fid: u32) void { + _ = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; + _ = s.settle() catch {}; + } -extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + fn dropNoWait(s: *Session, fid: u32) void { + const tag = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; + s.unwaited |= bit(tag); + s.flush() catch {}; + } -pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listener { - var name: [16]u8 = undefined; - // unreachable: a u32 is at most 10 digits - const fallback = std.fmt.bufPrint(&name, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable; - return listen(io, gpa, core, core.opts.ninep_name, fallback, core.opts.ninep_tcp) catch { - if (refusal.len > 0) core.setMessage(0, refusal) else core.reportError(0, "9p listener", error.ListenFailed); - return null; - }; -} + fn send(s: *Session, req: ninep.Client.Request) Error!u16 { + return s.cl.submit(req) catch Error.Botch; + } -/// What a pane shell is told about the editor above it, set into this -/// process's environment just before `forkpty` so the child inherits it. -/// -/// Two independent facts, and they are separate variables because they answer -/// separate questions. `PARDES_PID` says "you are inside this editor, and it -/// will take a Look from you": a session whose 9P listener never came up still -/// owns its children, so the child says so rather than looking, from its own -/// side, exactly like no pardes at all. `PARDES_9P` and `PARDES_PANE` say how -/// to reach it, and a `--nested` session exports them too — its socket stays -/// open to scripts and to mounted shells — while withholding `PARDES_PID`, -/// which is the whole of what `--nested` means. -/// -/// The socket is this process's own (`listen` keeps it, its listener's -/// path, until `deinit`), for a pane's shell and for a command run off the -/// loop (an Edit's filter) alike. Told to children through -/// host_io.ChildEnv, never set into this process's own environment (see -/// ChildEnv.exportVar for why). -pub fn exportEnv(serial: u32, adopts: bool) void { - const socket: ?[]const u8 = if (own_socket_len > 0) own_socket[0..own_socket_len] else null; - const ChildEnv = @import("host_io.zig").ChildEnv; - var pid_buf: [16]u8 = undefined; - ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable else null); // a u32 fits 16 - if (socket) |own| { - var buf: [16]u8 = undefined; - ChildEnv.exportVar("PARDES_9P", own); - exportMount(own); - ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); - return; - } - ChildEnv.exportVar("PARDES_9P", null); - ChildEnv.exportVar("PARDES_PANE", null); - ChildEnv.exportVar("PARDES_MOUNT", null); -} + fn newFid(s: *Session) u32 { + const fid = s.next_fid; + s.next_fid = if (fid >= 1 << 20) 1 else fid + 1; + return fid; + } -/// $PARDES_MOUNT, the session's own directory, when the environment says -/// where it is -- never by looking at the mount, which this editor serves -/// (the self-mount deadlock). Under `9ns --mntgen` (NINE_MNTGEN=1) it is -/// `$NINE_MOUNT/pardes/`, the name the registry gives the socket. -/// Any other $NINE_MOUNT is a mount of another server, made before this -/// session had a socket: unknown, so unset, and a script falls back to -/// `9p -a "unix!$PARDES_9P"`. -fn exportMount(sock_path: []const u8) void { - const mntgen = if (libc.getenv("NINE_MNTGEN")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; - const root = if (libc.getenv("NINE_MOUNT")) |v| std.mem.span(v) else ""; - const base = std.Io.Dir.path.basename(sock_path); - const sock_prefix = "pardes-9p-"; - const suffix = ".sock"; - if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { - var buf: [4096]u8 = undefined; - if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { - return @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", mount); - } else |_| {} - } - @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null); -} + /// A new connection's Tversion and Tattach, sent with the first + /// operation's requests behind them in one flight (`land`). + fn greet(s: *Session, f: *Flight) Error!void { + if (s.attached) return; + _ = f.add(.version, try s.send(.{ .version = .{} })); + // ponytail: cloud9's client submits nothing while a Tversion is + // out, so its msize is taken as asked until the Rversion lands + // (`land` puts it back); only a pardes is dialled here, and every + // one offers ninep.msize. A Twrite in this flight stays under the + // least a listener offers (`flight_write`). The fix is cloud9's + // client taking requests while it versions. + s.cl.versioning = false; + s.cl.msize = s.cl.asked; + _ = f.add(.attach, try s.send(.{ .attach = .{ .fid = 0, .uname = uname } })); + } -test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" { - const names = [_][*:0]const u8{ "NINE_MNTGEN", "NINE_MOUNT", "PARDES_MOUNT" }; - var saved: [names.len]?[:0]u8 = @splat(null); - for (names, &saved) |name, *value| { - if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); - } - defer for (names, saved) |name, value| { - if (value) |old| { - _ = setenv(name, old, 1); - testing.allocator.free(old); - } else _ = @import("host_io.zig").testUnsetenv(name); + /// The walk to a new fid at `names` (two Twalks past 16 names, the + /// second from the fid to itself), from the root. + fn walkNew(s: *Session, f: *Flight, names: []const []const u8) Error!u32 { + const fid = s.newFid(); + const first = names[0..@min(names.len, ninep.max_welem)]; + f.add(.walk, try s.send(.{ .walk = .{ .fid = 0, .newfid = fid, .names = first } })).asked = @intCast(first.len); + if (names.len > first.len) + f.add(.walk, try s.send(.{ .walk = .{ .fid = fid, .newfid = fid, .names = names[first.len..] } })).asked = @intCast(names.len - first.len); + return fid; + } + + /// Sends the flight and takes every answer of it, a read's bytes + /// into `taker` as they come (each valid only until the next), so + /// that the connection is left with nothing out but its clunks. A + /// refused Tversion is its words at once: nothing after it is + /// answered. + fn land(s: *Session, f: *Flight, taker: ?*Taker, remote: *RemoteError) Error!void { + if (f.get(.version) != null) s.cl.versioning = true; + while (f.open()) { + const done = try s.settle(); + const item = f.find(done.tag) orelse return Error.Botch; + item.done = true; + switch (done.result) { + .fail => |words| { + item.failed = true; + item.said.keep(words); + if (item.step == .version) return remote.set(words); + }, + .version => { + if (item.step != .version or s.cl.msize == 0) return Error.Botch; + }, + .attach => |qid| { + if (item.step != .attach) return Error.Botch; + s.root_qid = qid; + s.attached = true; + }, + .walk => |w| { + if (item.step != .walk) return Error.Botch; + item.n = w.nwqid; + if (w.nwqid > 0) item.qid = w.wqid[w.nwqid - 1]; + }, + .stat => |st| { + if (item.step != .stat) return Error.Botch; + item.n = st.length; + }, + .open => |o| { + if (item.step != .open) return Error.Botch; + item.qid = o.qid; + }, + .read => |data| { + if (item.step != .read) return Error.Botch; + item.n = data.len; + if (taker) |t| t.take(item, data); + // A read is timed by its progress, as a long write + // is: each answer gives the rest the budget again, so + // a large file over a slow link is not cut off. + s.deadline = @max(s.deadline, nowMs() +| budget_ms); + }, + .write => |count| { + if (item.step != .write) return Error.Botch; + item.n = count; + }, + else => return Error.Botch, + } + } + } }; - _ = setenv("NINE_MOUNT", "/mnt/9p", 1); - _ = setenv("NINE_MNTGEN", "1", 1); - exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?); - // A mount of another server (9ns --unix): not this session's. - _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN"); - exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null); -} -test "9P shell environment states being inside pardes apart from how to reach it" { - const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" }; - var saved: [names.len]?[:0]u8 = @splat(null); - for (names, &saved) |name, *value| { - if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); + fn bit(tag: u16) u32 { + return @as(u32, 1) << @intCast(tag); } - defer for (names, saved) |name, value| { - if (value) |old| { - _ = setenv(name, old, 1); - testing.allocator.free(old); - } else _ = @import("host_io.zig").testUnsetenv(name); - }; - var dir: [sun_path_len:0]u8 = undefined; - _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1); - try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?); - _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); - _ = setenv("HOME", "/home/example", 1); - try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); - _ = @import("host_io.zig").testUnsetenv("HOME"); - try testing.expect(socketDir(&dir) == null); + /// The requests of one flight, each its own tag, sent back to back: a + /// pardes takes one connection's requests in order (cloud9's engine + /// starts a request once the one before it is answered or parked), so + /// a walk, the open of its fid and the first read or write need no + /// answer between them, and an operation costs one round trip. + const Flight = struct { + items: [ninep.Client.window]Item = undefined, + len: usize = 0, - // The socket a listener keeps while it lives. - const path = "/tmp/pardes-example.sock"; - @memcpy(own_socket[0..path.len], path); - own_socket[path.len] = 0; - own_socket_len = path.len; - defer own_socket_len = 0; - var own: [16]u8 = undefined; - const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))}); + const Step = enum { version, attach, walk, stat, open, read, write }; + const Item = struct { + step: Step, + tag: u16, + done: bool = false, + failed: bool = false, + said: RemoteError = .{}, + /// walk: names asked; read: its offset and count. + asked: u16 = 0, + off: u64 = 0, + count: u32 = 0, + /// walk: qids answered; stat: the length; read, write: bytes. + n: u64 = 0, + qid: ninep.Qid = undefined, + }; - // A `--nested` session: reachable for scripts and mounts, but nobody's - // parent, so a pardes started in one of its shells runs a session of - // its own instead of handing its argument over. - exportEnv(7, false); - try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?); - try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); + fn add(f: *Flight, step: Step, tag: u16) *Item { + f.items[f.len] = .{ .step = step, .tag = tag }; + f.len += 1; + return &f.items[f.len - 1]; + } - exportEnv(8, true); - try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); - try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); + fn find(f: *Flight, tag: u16) ?*Item { + for (f.items[0..f.len]) |*item| if (item.tag == tag and !item.done) return item; + return null; + } - // A session whose listener never came up is still the session this shell - // is inside: the pid stands on its own, and only the address is missing. - own_socket_len = 0; - exportEnv(0, true); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); - try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); + fn get(f: *Flight, step: Step) ?*Item { + for (f.items[0..f.len]) |*item| if (item.step == step) return item; + return null; + } - exportEnv(0, false); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); - try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); -} + fn open(f: *const Flight) bool { + for (f.items[0..f.len]) |item| if (!item.done) return true; + return false; + } -pub const Client = struct { - pub const budget_ms: i64 = 2000; - /// Each write of a long one has this long to be answered (transact). - pub const write_budget_ms: i64 = 30_000; + /// The first refusal in the order asked: a version's or an attach's + /// words, a walk short of its names, an open's refusal. + fn check(f: *Flight, remote: *RemoteError) Error!void { + for (f.items[0..f.len]) |*item| switch (item.step) { + .version, .attach, .open => if (item.failed) return remote.set(item.said.buf[0..item.said.len]), + .walk => { + if (item.failed) return remote.set(item.said.buf[0..item.said.len]); + if (item.n != item.asked) return Error.NotFound; + }, + .stat, .read, .write => {}, + }; + } - pub const max_depth: usize = 2 * ninep.max_welem; + /// The walked file's qid: the last walk's, or the root's for none. + fn qid(f: *Flight, root: ninep.Qid) ninep.Qid { + var at = root; + for (f.items[0..f.len]) |item| if (item.step == .walk and item.n > 0) { + at = item.qid; + }; + return at; + } - const uname = "pardes"; + /// Whether the walk made the fid, so that it is owed a clunk. + fn made(f: *Flight) bool { + const first = f.get(.walk) orelse return false; + return !first.failed and first.n == first.asked; + } + }; - const Dial = union(enum) { unix: [:0]const u8, tcp: std.Io.net.IpAddress }; + /// A write in a new connection's first flight is sent before the msize + /// is known: no larger than the least a pardes listener offers. + const flight_write = ninep.min_msize - 23; - pub const Error = error{ - PathTooDeep, - BadDial, - Dial, - Hangup, - Timeout, - Botch, - Remote, - IsDirectory, - NotFound, - FileTooLarge, + /// Reads ahead this many Treads at once (the window, less a clunk + /// still out and one spare). + const read_ahead = ninep.Client.window - 2; + + /// Version and attach on a new connection, and a walk to `names`, in + /// one flight: the fid there. + fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !u32 { + var f: Flight = .{}; + try s.greet(&f); + const fid = try s.walkNew(&f, names); + try s.land(&f, null, remote); + f.check(remote) catch |err| { + if (f.made()) s.dropNoWait(fid); + return err; + }; + return fid; + } + + /// A read's bytes taken in order: a file's as they are, a directory's + /// entries as rows of names. A read ahead that came back out of order, + /// or past one that came back short, is not taken: what it held is + /// read again from where the taken bytes end. + const Taker = struct { + out: *std.Io.Writer.Allocating, + display_path: []const u8, + limit: usize, + /// The flight with the walk, whose answer says what was reached: + /// it lands before any read (a walk never parks). + flight: *Flight, + s: *const Session, + /// Bytes taken from the start; a directory's next offset. + end: u64 = 0, + /// The read that ended at `end` came back short, or empty (the end). + short: bool = false, + empty: bool = false, + /// What taking said (too large, a bad entry): the operation's + /// answer once every read out has landed. + err: ?Error = null, + + fn take(t: *Taker, item: *Flight.Item, data: []const u8) void { + if (t.err != null or item.off != t.end or t.short) return; + t.put(data) catch |err| { + t.err = err; + return; + }; + t.end += data.len; + t.short = data.len < item.count; + t.empty = data.len == 0; + } + + fn directory(t: *const Taker) bool { + return t.flight.qid(t.s.root_qid).type & ninep.qtdir != 0; + } + + fn maxBytes(t: *const Taker) u64 { + return @min(t.limit, @as(usize, if (t.directory()) limits.max_stream_bytes else limits.max_file_bytes)); + } + + fn wireLimit(t: *const Taker) u64 { + return if (t.directory()) limits.max_stream_bytes else t.maxBytes(); + } + + fn put(t: *Taker, data: []const u8) Error!void { + if (t.end + data.len > t.wireLimit()) return Error.FileTooLarge; + if (t.directory()) { + var pos: usize = 0; + while (pos < data.len) { + if (data.len - pos < 2) return Error.Botch; + const len: usize = 2 + @as(usize, std.mem.readInt(u16, data[pos..][0..2], .little)); + if (len > data.len - pos) return Error.Botch; + const entry = ninep.Stat.decode(data[pos..][0..len]) catch return Error.Botch; + const display_dir = std.mem.trimEnd(u8, t.display_path, "/"); + const row_len = display_dir.len + entry.name.len + 2 + @as(usize, @intFromBool(entry.qid.type & ninep.qtdir != 0)); + if (row_len > t.maxBytes() - t.out.written().len) return Error.FileTooLarge; + t.out.writer.print("{s}/{s}", .{ display_dir, entry.name }) catch return Error.Botch; + if (entry.qid.type & ninep.qtdir != 0) t.out.writer.writeByte('/') catch return Error.Botch; + t.out.writer.writeByte('\n') catch return Error.Botch; + pos += len; + } + } else t.out.writer.writeAll(data) catch return Error.Botch; + } }; - pub fn read(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8) ![]u8 { - return readLimit(gpa, dial, path, display_path, limits.max_file_bytes); - } + /// One operation in as few round trips as its answers allow: the walk, + /// a read's stat, the open and the first read or write go in one flight + /// (behind a new connection's version and attach). A file of the + /// length its stat said is whole when a read comes back short at that + /// length; a longer one is read ahead, the Treads for the rest sent at + /// once. Anything else (a directory, a file of no stated length) reads + /// on until a read comes back empty, the only end 9P has. + fn transact( + s: *Session, + names: []const []const u8, + out: *std.Io.Writer.Allocating, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + ) !void { + const writing = write_bytes != null; + const mode: u8 = if (writing) ninep.owrite else ninep.oread; + const truncate = writing and names.len > 0 and + (std.mem.eql(u8, names[0], "os") or std.mem.eql(u8, names[names.len - 1], "body")); + const fresh = !s.attached; + var f: Flight = .{}; + try s.greet(&f); + const fid = try s.walkNew(&f, names); + if (!writing) _ = f.add(.stat, try s.send(.{ .stat = .{ .fid = fid } })); + _ = f.add(.open, try s.send(.{ .open = .{ .fid = fid, .mode = mode | if (truncate) ninep.otrunc else 0 } })); + const chunk_max: usize = if (fresh) flight_write else s.cl.maxWrite(); + const first: []const u8 = if (write_bytes) |bytes| bytes[0..@min(bytes.len, chunk_max)] else ""; + if (writing and first.len != 0) { + // Out of the client's buffer first (it holds one msize): still + // sent without waiting. + try s.flush(); + _ = f.add(.write, try s.send(.{ .write = .{ .fid = fid, .offset = 0, .data = first } })); + } + // A read's count before the msize is known is the asked msize's. + if (!writing) { + const item = f.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } })); + item.count = s.cl.maxRead(); + } + var taker: Taker = .{ .out = out, .display_path = s.display_path, .limit = read_limit, .flight = &f, .s = s }; + try s.land(&f, &taker, remote); + defer if (f.made()) s.dropNoWait(fid); + try f.check(remote); + if (taker.err) |err| return err; + const directory = taker.directory(); - pub fn readLimit(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { - return fetch(false, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); - } + if (write_bytes) |bytes| { + if (directory) return Error.IsDirectory; + var written: usize = 0; + if (f.get(.write)) |w| { + // Refused unopened, the open parked (a truncating one while + // the editor is out): sent again below, after it. + if (w.failed and !std.mem.eql(u8, w.said.buf[0..w.said.len], ninep.fs.e_bad_use)) return remote.set(w.said.buf[0..w.said.len]); + if (!w.failed) { + if (w.n == 0 or w.n > first.len) return Error.Botch; + written = w.n; + } + } + while (written < bytes.len) { + s.deadline = nowMs() +| write_budget_ms; + const chunk = bytes[written..][0..@min(bytes.len - written, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + // A long write is timed by its progress: each answer gives + // the next its own budget, so a large body (`pardes -`) goes + // in through one open, whole, however long it takes. The + // budget is a write's: a server putting in tens of MiB it + // held (pane.zig batchFor) answers that one write late. + } + return; + } - /// readLimit through a mount: its connection kept for the next (`kept`). - pub fn readMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { - return fetch(true, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); + if (f.get(.read)) |r| if (r.failed and !std.mem.eql(u8, r.said.buf[0..r.said.len], ninep.fs.e_bad_use)) + return remote.set(r.said.buf[0..r.said.len]); + const length: u64 = if (f.get(.stat)) |st| (if (st.failed or directory) 0 else st.n) else 0; + const step: u64 = s.cl.maxRead(); + while (true) { + if (taker.empty) return; + if (taker.short and length != 0 and taker.end == length) return; + // The rest of a file of known length at once; a directory, a + // file of none, or the end to be seen, a read at a time. + // ponytail: a file of no stated length is not read ahead. + const want: u64 = if (directory or taker.short or length <= taker.end) 1 else @min(read_ahead, (length - taker.end) / step + 1); + var batch: Flight = .{}; + var off = taker.end; + for (0..want) |_| { + if (off > taker.wireLimit()) break; + const count: u32 = @intCast(@min(step, taker.wireLimit() + 1 - off)); + const item = batch.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = off, .count = count } })); + item.off = off; + item.count = count; + off += count; + } + taker.short = false; + try s.land(&batch, &taker, remote); + if (taker.err) |err| return err; + for (batch.items[0..batch.len]) |item| if (item.failed and item.off == taker.end and !taker.short) + return remote.set(item.said.buf[0..item.said.len]); + } } - /// One operation on `path`, a read of up to `read_limit` or a write of - /// `write_bytes`, on the connection kept for `dial` when `keep`: the - /// peer's words, when it refuses, kept for lastSaid. - fn fetch(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, write_bytes: ?[]const u8, read_limit: usize) ![]u8 { - if (comptime !supported) return error.Unsupported; - var names: [max_depth][]const u8 = undefined; - const n = try elements(path, &names); - var remote: RemoteError = .{}; - return fetchBytes(gpa, dial, names[0..n], &remote, write_bytes, display_path, read_limit, keep) catch |err| { - if (err == error.Remote) said = remote; - return err; + fn fetchBytes( + gpa: std.mem.Allocator, + dial: []const u8, + names: []const []const u8, + remote: *RemoteError, + write_bytes: ?[]const u8, + display_path: []const u8, + read_limit: usize, + keep: bool, + ) ![]u8 { + if (comptime !supported) return Error.Dial; + if (keep) if (kept.take(dial)) |s| { + if (fetchOn(s, gpa, names, remote, write_bytes, read_limit, display_path, true)) |bytes| return bytes else |err| switch (err) { + // Let go of by the peer since (its hangup still on the way): + // a read is asked again on a new connection. A write is not, + // as it may have been done. + error.Hangup, error.Botch => if (write_bytes != null) return err, + else => return err, + } }; + return fetchOn(try startSession(dial, display_path), gpa, names, remote, write_bytes, read_limit, display_path, keep); } - /// The peer's own words for the last error.Remote a read or write here - /// got (its Rerror), for a caller that says why: this thread's, as the - /// editor's mounts and a Handover job each ask from their own. - threadlocal var said: RemoteError = .{}; - pub fn lastSaid() []const u8 { - return said.buf[0..said.len]; - } - - /// Whether a peer answers at `dial`: a version and attach, and its root - /// read. Any answer from the peer, an error of its own included, is one. - pub fn probe(gpa: std.mem.Allocator, dial: []const u8) !void { - return probeWith(false, gpa, dial); + fn fetchOn( + s: *Session, + gpa: std.mem.Allocator, + names: []const []const u8, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + display_path: []const u8, + keep: bool, + ) ![]u8 { + s.deadline = nowMs() +| budget_ms; + s.display_path = display_path; + var clean = false; + defer endSession(s, keep and clean); + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + transact(s, names, &out, remote, write_bytes, read_limit) catch |err| { + // Refused with every answer in: the connection is as good as before. + clean = switch (err) { + error.Remote, error.NotFound, error.IsDirectory, error.FileTooLarge => true, + else => false, + }; + return err; + }; + clean = true; + return out.toOwnedSlice(); } - /// probe for a Mount: the connection kept as the mount's. - pub fn probeMount(gpa: std.mem.Allocator, dial: []const u8) !void { - return probeWith(true, gpa, dial); + /// A new connection at `dial` whose requests have the usual deadline. + fn startSession(dial: []const u8, display_path: []const u8) !*Session { + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); + const deadline = nowMs() +| budget_ms; + // Not the caller's allocator: a kept one outlives the call (an arena's). + const s = try std.heap.page_allocator.create(Session); + s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; + errdefer endSession(s, false); + s.fd = try connect(sock, deadline); + s.cl = .init(.{ .in = &s.in, .out = &s.out }); + if (dial.len <= s.dial_buf.len) { + @memcpy(s.dial_buf[0..dial.len], dial); + s.dial_len = dial.len; + } + return s; } - fn probeWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8) !void { - const got = fetch(keep, gpa, dial, "", "", null, 0) catch |err| switch (err) { - error.IsDirectory, error.NotFound, error.Remote, error.FileTooLarge => return, - else => return err, - }; - gpa.free(got); + fn endSession(s: *Session, keep: bool) void { + if (keep and s.attached and s.dial_len != 0 and kept.put(s)) return; + if (s.fd >= 0) _ = libc.close(s.fd); + std.heap.page_allocator.destroy(s); } - pub fn write(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { - gpa.free(try fetch(false, gpa, dial, path, path, bytes, limits.max_file_bytes)); - } + /// Connections kept open between operations, a few dials' (a mount's, + /// as Plan 9's mount keeps its channel): each costs the peer one of its + /// `max_conns` while kept, so only mounts and the Mount probe keep one. + const kept = struct { + const max = 8; + var lock: std.atomic.Mutex = .unlocked; + var slots: [max]?*Session = @splat(null); - /// write through a mount: its connection kept for the next (`kept`). - pub fn writeMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { - gpa.free(try fetch(true, gpa, dial, path, path, bytes, limits.max_file_bytes)); - } + fn hold() void { + while (!lock.tryLock()) std.atomic.spinLoopHint(); + } - const RemoteError = struct { - buf: [ninep.errmax]u8 = undefined, - len: usize = 0, + /// The session kept for `dial`, out of the table, if it is still + /// there: what came while it waited (a clunk's answer) taken, and + /// a hangup or anything else seen as its end. + fn take(dial: []const u8) ?*Session { + hold(); + const s = for (&slots) |*slot| { + const got = slot.* orelse continue; + if (std.mem.eql(u8, got.dial_buf[0..got.dial_len], dial)) { + slot.* = null; + break got; + } + } else null; + lock.unlock(); + const found = s orelse return null; + if (usable(found)) return found; + endSession(found, false); + return null; + } - fn set(r: *RemoteError, msg: []const u8) error{Remote} { - r.keep(msg); - return error.Remote; + fn usable(s: *Session) bool { + while (true) { + var fds = [1]libc.pollfd{.{ .fd = s.fd, .events = poll_in, .revents = 0 }}; + if (libc.poll(&fds, 1, 0) < 0) return false; + if (fds[0].revents == 0) return true; + if (fds[0].revents & poll_in == 0) return false; + const room = s.cl.in.len - s.cl.in_len; + if (room == 0) return false; + const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return false) orelse return true; + if (got == 0) return false; + _ = s.cl.push(s.stage[0..got]); + while (s.cl.take()) |done| { + if (done.tag >= 32 or s.unwaited & bit(done.tag) == 0) return false; + s.unwaited &= ~bit(done.tag); + } + if (s.cl.dead) return false; + } } - fn keep(r: *RemoteError, msg: []const u8) void { - r.len = @min(msg.len, r.buf.len); - @memcpy(r.buf[0..r.len], msg[0..r.len]); + fn put(s: *Session) bool { + hold(); + defer lock.unlock(); + for (&slots) |*slot| if (slot.* == null) { + slot.* = s; + return true; + }; + return false; } }; - fn elements(path: []const u8, out: *[max_depth][]const u8) Error!usize { - var n: usize = 0; - var it = std.mem.tokenizeScalar(u8, path, '/'); - while (it.next()) |name| { - if (n == out.len) return Error.PathTooDeep; - out[n] = name; - n += 1; + /// Lets go of a connection kept for `dial` (an Unmount): its mount is gone. + pub fn forget(dial: []const u8) void { + if (comptime !supported) return; + while (kept.take(dial)) |s| endSession(s, false); + } + + /// Writes `request`, then `more`, to `path` and reads the answer on the + /// same open, as /pane/new answers its own open: a session's last + /// answer, from another client, can never be what comes back. `exec + /// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in + /// Twrites at rising offsets, each answer giving the next its budget. + pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + errdefer said = remote; + const s = try startSession(dial, path); + defer endSession(s, false); + const fid = try walkTo(s, names[0..n], &remote); + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + var written: usize = 0; + while (written < request.len + more.len) { + const from = if (written < request.len) request[written..] else more[written - request.len ..]; + const chunk = from[0..@min(from.len, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + s.deadline = nowMs() +| write_budget_ms; + } + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = out.items.len, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return out.toOwnedSlice(gpa); + if (out.items.len + data.len > 4096) return Error.FileTooLarge; + try out.appendSlice(gpa, data); } - return n; } - fn resolve(buf: *[sun_path_len]u8, dial: []const u8) error{BadDial}!Dial { - if (dial.len == 0) return error.BadDial; - if (std.mem.startsWith(u8, dial, "tcp!")) return .{ .tcp = try networkAddress(dial, false) }; - const explicit_unix = std.mem.startsWith(u8, dial, "unix!"); - // A network this does not dial (`nowhere!x`) is a malformed address, - // not a session named so. - if (!explicit_unix and std.mem.indexOfScalar(u8, dial, '/') == null and std.mem.indexOfScalar(u8, dial, '!') != null) return error.BadDial; - const path = if (explicit_unix) dial[5..] else dial; - if (explicit_unix and !std.mem.startsWith(u8, path, "/")) return error.BadDial; - if (std.mem.indexOfScalar(u8, path, '/') != null) { - // A socket's path is absolute: a relative one would mean wherever - // the editor happens to run. - if (path[0] != '/') return error.BadDial; - if (std.mem.indexOfScalar(u8, path, 0) != null) return error.BadDial; - return .{ .unix = std.fmt.bufPrintSentinel(buf, "{s}", .{path}, 0) catch return error.BadDial }; + /// Opens `path` on one connection and writes `first` to it (/log's + /// `follow new`), all with the usual deadline; then, once `ready(ctx)` + /// has said it is not done already, reads it with no deadline, a read at + /// a time, until `record(ctx, bytes)` says done. An end of file or a + /// dropped connection is Hangup. What `pardes --wait` blocks on. + pub fn follow( + dial: []const u8, + path: []const u8, + first: []const u8, + ctx: anytype, + comptime ready: fn (@TypeOf(ctx)) bool, + comptime record: fn (@TypeOf(ctx), []const u8) bool, + ) !void { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + const s = try startSession(dial, path); + defer endSession(s, false); + const fid = try walkTo(s, names[0..n], &remote); + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); + if (ready(ctx)) return; + s.deadline = std.math.maxInt(i64); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return Error.Hangup; + if (record(ctx, data)) return; } - var dir_buf: [sun_path_len:0]u8 = undefined; - const dir = socketDir(&dir_buf) orelse return error.BadDial; - return .{ .unix = socketPath(buf, dir, dial) orelse return error.BadDial }; } - pub fn validateDial(dial: []const u8) error{BadDial}!void { - var buf: [sun_path_len]u8 = undefined; - _ = try resolve(&buf, dial); + fn connect(sock: Dial, deadline: i64) Error!c_int { + const address: transport.Address = switch (sock) { + .unix => |path| .{ .unix = path }, + .tcp => |ip| .{ .tcp = ip }, + }; + return transport.connectFd(address, deadline) catch return Error.Dial; } - const Session = struct { - fd: c_int, - deadline: i64, - display_path: []const u8, - cl: ninep.Client = undefined, - in: [msize]u8 = undefined, - out: [msize]u8 = undefined, - stage: [msize]u8 = undefined, - /// Version and attach answered: fid 0 is the peer's root, and each - /// operation walks a fid of its own from it, so a kept connection - /// (`kept`) pays for neither again. - attached: bool = false, - root_qid: ninep.Qid = undefined, - next_fid: u32 = 1, - /// Tags whose answers nobody waits for (a clunk's): dropped by - /// whoever settles next. - unwaited: u32 = 0, - /// The dial a kept connection answers for. - dial_buf: [sun_path_len + 32]u8 = undefined, - dial_len: usize = 0, + const poll_in: i16 = @intCast(libc.POLL.IN); + const poll_out: i16 = @intCast(libc.POLL.OUT); - fn wait(s: *Session, events: i16) Error!void { - if (s.deadline - nowMs() <= 0) return Error.Timeout; - return transport.wait(s.fd, events, s.deadline) catch |err| switch (err) { - error.Timeout => Error.Timeout, - else => Error.Hangup, - }; - } + test "a path becomes walk elements, normalised the way a shell would" { + var out: [max_depth][]const u8 = undefined; + try testing.expectEqual(@as(usize, 3), try elements("/pane/1/body", &out)); + try testing.expectEqualStrings("pane", out[0]); + try testing.expectEqualStrings("1", out[1]); + try testing.expectEqualStrings("body", out[2]); - fn flush(s: *Session) Error!void { - while (s.cl.output().len != 0) { - if (nowMs() >= s.deadline) return Error.Timeout; - const bytes = s.cl.output(); - try s.wait(poll_out); - const sent = (transport.write(s.fd, bytes) catch return Error.Hangup) orelse continue; - s.cl.wrote(@intCast(sent)); - } - } + try testing.expectEqual(@as(usize, 3), try elements("pane/1/body", &out)); + try testing.expectEqual(@as(usize, 3), try elements("//pane//1//body//", &out)); + try testing.expectEqual(@as(usize, 1), try elements("/index", &out)); - fn settle(s: *Session) Error!ninep.Client.Done { - while (true) { - if (nowMs() >= s.deadline) return Error.Timeout; - try s.flush(); - if (s.cl.take()) |done| { - if (done.tag < 32 and s.unwaited & bit(done.tag) != 0) { - s.unwaited &= ~bit(done.tag); - continue; - } - return done; - } - if (s.cl.dead) return Error.Botch; - const room = s.cl.in.len - s.cl.in_len; - if (room == 0) return Error.Botch; - try s.wait(poll_in); - const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return Error.Hangup) orelse continue; - if (got == 0) return Error.Hangup; - const n = s.cl.push(s.stage[0..@intCast(got)]); - std.debug.assert(n == @as(usize, @intCast(got))); - } - } + try testing.expectEqual(@as(usize, 0), try elements("/", &out)); - fn ask(s: *Session, req: ninep.Client.Request, remote: *RemoteError) Error!ninep.Client.Result { - _ = s.cl.submit(req) catch return Error.Botch; - const done = try s.settle(); - if (done.result == .fail) return remote.set(done.result.fail); - if (std.mem.eql(u8, @tagName(done.result), @tagName(std.meta.activeTag(req)))) return done.result; - return Error.Botch; - } + var deep: [8 * max_depth]u8 = @splat('/'); + for (0..max_depth + 1) |i| deep[i * 2 + 1] = 'a'; + try testing.expectError(Error.PathTooDeep, elements(deep[0 .. (max_depth + 1) * 2], &out)); + } - fn drop(s: *Session, fid: u32) void { - _ = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; - _ = s.settle() catch {}; - } + test "a bare dial resolves to the socket --9p binds, and a path is taken as given" { + if (comptime !supported) return error.SkipZigTest; + var buf: [sun_path_len]u8 = undefined; - fn dropNoWait(s: *Session, fid: u32) void { - const tag = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; - s.unwaited |= bit(tag); - s.flush() catch {}; - } + const named = (try resolve(&buf, "work")).unix; + try testing.expect(std.mem.endsWith(u8, named, "/pardes-9p-work.sock")); + var expect: [sun_path_len]u8 = undefined; + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf).?; + try testing.expectEqualStrings(socketPath(&expect, dir, "work").?, named); - fn send(s: *Session, req: ninep.Client.Request) Error!u16 { - return s.cl.submit(req) catch Error.Botch; - } + const path = (try resolve(&buf, "/tmp/somewhere.sock")).unix; + try testing.expectEqualStrings("/tmp/somewhere.sock", path); + try testing.expectEqualStrings("/tmp/somewhere.sock", (try resolve(&buf, "unix!/tmp/somewhere.sock")).unix); - fn newFid(s: *Session) u32 { - const fid = s.next_fid; - s.next_fid = if (fid >= 1 << 20) 1 else fid + 1; - return fid; - } + try testing.expectError(error.BadDial, resolve(&buf, "")); + try testing.expectError(error.BadDial, resolve(&buf, "/tmp/a\x00b")); + } - /// A new connection's Tversion and Tattach, sent with the first - /// operation's requests behind them in one flight (`land`). - fn greet(s: *Session, f: *Flight) Error!void { - if (s.attached) return; - _ = f.add(.version, try s.send(.{ .version = .{} })); - // ponytail: cloud9's client submits nothing while a Tversion is - // out, so its msize is taken as asked until the Rversion lands - // (`land` puts it back); only a pardes is dialled here, and every - // one offers ninep.msize. A Twrite in this flight stays under the - // least a listener offers (`flight_write`). The fix is cloud9's - // client taking requests while it versions. - s.cl.versioning = false; - s.cl.msize = s.cl.asked; - _ = f.add(.attach, try s.send(.{ .attach = .{ .fid = 0, .uname = uname } })); - } + test "a dial with nothing listening is one error and not a wait" { + if (comptime !supported) return error.SkipZigTest; + var names: [max_depth][]const u8 = undefined; + const n = try elements("/pane/1/body", &names); + var remote: RemoteError = .{}; + const before = nowMs(); + try testing.expectError( + Error.Dial, + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes, false), + ); + try testing.expect(nowMs() - before < budget_ms); + } - /// The walk to a new fid at `names` (two Twalks past 16 names, the - /// second from the fid to itself), from the root. - fn walkNew(s: *Session, f: *Flight, names: []const []const u8) Error!u32 { - const fid = s.newFid(); - const first = names[0..@min(names.len, ninep.max_welem)]; - f.add(.walk, try s.send(.{ .walk = .{ .fid = 0, .newfid = fid, .names = first } })).asked = @intCast(first.len); - if (names.len > first.len) - f.add(.walk, try s.send(.{ .walk = .{ .fid = fid, .newfid = fid, .names = names[first.len..] } })).asked = @intCast(names.len - first.len); - return fid; - } + test "one fetch has three msize buffers and bounded transport metadata" { + try testing.expectEqual(@as(usize, msize), @as(usize, (Session{ .fd = -1, .deadline = 0, .display_path = "" }).in.len)); + try testing.expect(@sizeOf(Session) <= 3 * msize + @sizeOf(ninep.Client) + 128 + @sizeOf(@FieldType(Session, "dial_buf"))); + try testing.expect(@sizeOf(ninep.Client) <= 512); + } - /// Sends the flight and takes every answer of it, a read's bytes - /// into `taker` as they come (each valid only until the next), so - /// that the connection is left with nothing out but its clunks. A - /// refused Tversion is its words at once: nothing after it is - /// answered. - fn land(s: *Session, f: *Flight, taker: ?*Taker, remote: *RemoteError) Error!void { - if (f.get(.version) != null) s.cl.versioning = true; - while (f.open()) { - const done = try s.settle(); - const item = f.find(done.tag) orelse return Error.Botch; - item.done = true; - switch (done.result) { - .fail => |words| { - item.failed = true; - item.said.keep(words); - if (item.step == .version) return remote.set(words); - }, - .version => { - if (item.step != .version or s.cl.msize == 0) return Error.Botch; - }, - .attach => |qid| { - if (item.step != .attach) return Error.Botch; - s.root_qid = qid; - s.attached = true; - }, - .walk => |w| { - if (item.step != .walk) return Error.Botch; - item.n = w.nwqid; - if (w.nwqid > 0) item.qid = w.wqid[w.nwqid - 1]; - }, - .stat => |st| { - if (item.step != .stat) return Error.Botch; - item.n = st.length; - }, - .open => |o| { - if (item.step != .open) return Error.Botch; - item.qid = o.qid; - }, - .read => |data| { - if (item.step != .read) return Error.Botch; - item.n = data.len; - if (taker) |t| t.take(item, data); - // A read is timed by its progress, as a long write - // is: each answer gives the rest the budget again, so - // a large file over a slow link is not cut off. - s.deadline = @max(s.deadline, nowMs() +| budget_ms); - }, - .write => |count| { - if (item.step != .write) return Error.Botch; - item.n = count; - }, - else => return Error.Botch, - } - } - } - }; + test "expired sessions do not send or consume buffered protocol work" { + var session: Session = .{ .fd = -1, .deadline = 0, .display_path = "" }; + session.cl = .init(.{ .in = &session.in, .out = &session.out }); + _ = try session.cl.submit(.{ .version = .{} }); + const queued = session.cl.output().len; + try testing.expect(queued > 0); + try testing.expectError(Error.Timeout, session.flush()); + try testing.expectEqual(queued, session.cl.output().len); + try testing.expectError(Error.Timeout, session.settle()); + try testing.expectError(Error.Timeout, session.wait(poll_in)); + } +}; - fn bit(tag: u16) u32 { - return @as(u32, 1) << @intCast(tag); +fn bindSocket(path: [:0]const u8) c_int { + const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0); + if (fd < 0) return fd; + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); + if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) { + _ = libc.close(fd); + return -1; } + return fd; +} - /// The requests of one flight, each its own tag, sent back to back: a - /// pardes takes one connection's requests in order (cloud9's engine - /// starts a request once the one before it is answered or parked), so - /// a walk, the open of its fid and the first read or write need no - /// answer between them, and an operation costs one round trip. - const Flight = struct { - items: [ninep.Client.window]Item = undefined, - len: usize = 0, +test "the socket name is a third prefix in the shared directory" { + var buf: [sun_path_len]u8 = undefined; + const p = socketPath(&buf, "/run/user/1000", "t9srv").?; + try testing.expectEqualStrings("/run/user/1000/pardes-9p-t9srv.sock", p); + try testing.expect(!std.mem.startsWith(u8, std.Io.Dir.path.basename(p), "pardes-detached-")); +} - const Step = enum { version, attach, walk, stat, open, read, write }; - const Item = struct { - step: Step, - tag: u16, - done: bool = false, - failed: bool = false, - said: RemoteError = .{}, - /// walk: names asked; read: its offset and count. - asked: u16 = 0, - off: u64 = 0, - count: u32 = 0, - /// walk: qids answered; stat: the length; read, write: bytes. - n: u64 = 0, - qid: ninep.Qid = undefined, - }; +test "a name that is not one path component is no address at all" { + var buf: [sun_path_len]u8 = undefined; + try testing.expect(socketPath(&buf, "/run", "") == null); + try testing.expect(socketPath(&buf, "/run", "a/b") == null); + try testing.expect(socketPath(&buf, "/run", "a\x00b") == null); +} - fn add(f: *Flight, step: Step, tag: u16) *Item { - f.items[f.len] = .{ .step = step, .tag = tag }; - f.len += 1; - return &f.items[f.len - 1]; - } +test "the startup sweep removes a dead pid's socket and leaves a live pid's, a named one and a plain file" { + if (comptime !supported) return error.SkipZigTest; + var dir_buf: [sun_path_len:0]u8 = undefined; + const base = socketDir(&dir_buf) orelse return error.SkipZigTest; + if (!ensureSocketDir(base)) return error.SkipZigTest; + var sub_buf: [sun_path_len:0]u8 = undefined; + const sub = std.fmt.bufPrintSentinel(&sub_buf, "{s}/deadsweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch return error.SkipZigTest; + if (libc.mkdir(sub, 0o700) != 0) return error.SkipZigTest; + var paths: [4][sun_path_len:0]u8 = undefined; + // No process has this pid: kill(pid, 0) answers ESRCH. + const dead = try std.fmt.bufPrintSentinel(&paths[0], "{s}/" ++ prefix ++ "2147483647.sock", .{sub}, 0); + const live = try std.fmt.bufPrintSentinel(&paths[1], "{s}/" ++ prefix ++ "{d}.sock", .{ sub, @as(u32, @intCast(std.c.getppid())) }, 0); + const named = try std.fmt.bufPrintSentinel(&paths[2], "{s}/" ++ prefix ++ "work.sock", .{sub}, 0); + const plain = try std.fmt.bufPrintSentinel(&paths[3], "{s}/" ++ prefix ++ "2147483646.sock", .{sub}, 0); + defer { + for ([_][:0]const u8{ dead, live, named, plain }) |p| _ = libc.unlink(p); + _ = libc.rmdir(sub); + } + for ([_][:0]const u8{ dead, live, named }) |p| { + const fd = bindSocket(p); + if (fd < 0) return error.SkipZigTest; + _ = libc.close(fd); // closed: what a killed editor leaves + } + const fd = libc.open(plain, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); + if (fd < 0) return error.SkipZigTest; + _ = libc.close(fd); + sweepDeadSockets(testing.io, sub); + try testing.expect(statNoFollow(dead) == null); + try testing.expect(statNoFollow(live) != null); + try testing.expect(statNoFollow(named) != null); + try testing.expect(statNoFollow(plain) != null); +} - fn find(f: *Flight, tag: u16) ?*Item { - for (f.items[0..f.len]) |*item| if (item.tag == tag and !item.done) return item; - return null; - } +test "the registry sweep takes the dead entries and leaves everything else" { + if (comptime !supported) return error.SkipZigTest; + // Under the real runtime directory, because a sun_path is 108 bytes + // and the test cache's temporary directories are longer than that. + var dir_buf: [sun_path_len:0]u8 = undefined; + const base = socketDir(&dir_buf) orelse return error.SkipZigTest; + if (!ensureSocketDir(base)) return error.SkipZigTest; - fn get(f: *Flight, step: Step) ?*Item { - for (f.items[0..f.len]) |*item| if (item.step == step) return item; - return null; - } + var svc_buf: [sun_path_len:0]u8 = undefined; + const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/sweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch + return error.SkipZigTest; + if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest; - fn open(f: *const Flight) bool { - for (f.items[0..f.len]) |item| if (!item.done) return true; - return false; - } + // The sockets live where the real ones do -- beside the registry, not in + // it, and named the way a session names them -- because the sweep only + // follows an entry to a target of exactly that shape and place. + var paths: [6][sun_path_len:0]u8 = undefined; + const pid: u32 = @intCast(libc.getpid()); + const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/pardes-9p-sweeplive-{d}.sock", .{ base, pid }, 0); + const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/pardes-9p-sweepdead-{d}.sock", .{ base, pid }, 0); + const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0); + const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0); + const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0); + // A dead entry pointing at something that is NOT one of our sockets: the + // entry goes, the file it named must not. + const outsider_sock = try std.fmt.bufPrintSentinel(&paths[5], "{s}/sweep-outsider-{d}.sock", .{ base, pid }, 0); + var outsider_buf: [sun_path_len:0]u8 = undefined; + const outsider = try std.fmt.bufPrintSentinel(&outsider_buf, "{s}/outsider", .{svc}, 0); + // Live, its lock held, but bound and not listening: a connect is + // refused, on every system, as FreeBSD refuses one to a live session + // whose queue is full. Its lock is what says it lives. + var starting_paths: [2][sun_path_len:0]u8 = undefined; + const starting_sock = try std.fmt.bufPrintSentinel(&starting_paths[0], "{s}/pardes-9p-sweepstarting-{d}.sock", .{ base, pid }, 0); + const starting = try std.fmt.bufPrintSentinel(&starting_paths[1], "{s}/starting", .{svc}, 0); + var locks: [3][lock_path_len:0]u8 = undefined; + const dead_lock = lockPath(&locks[2], dead_sock).?; + defer { + for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger, outsider_sock, outsider, starting_sock, starting, dead_lock }) |p| _ = libc.unlink(p); + _ = libc.rmdir(svc); + } - /// The first refusal in the order asked: a version's or an attach's - /// words, a walk short of its names, an open's refusal. - fn check(f: *Flight, remote: *RemoteError) Error!void { - for (f.items[0..f.len]) |*item| switch (item.step) { - .version, .attach, .open => if (item.failed) return remote.set(item.said.buf[0..item.said.len]), - .walk => { - if (item.failed) return remote.set(item.said.buf[0..item.said.len]); - if (item.n != item.asked) return Error.NotFound; - }, - .stat, .read, .write => {}, - }; - } + const live_lock = claim(live_sock, &locks[0]) orelse return error.LockFailed; + defer release(live_lock, std.mem.sliceTo(&locks[0], 0)); + const listening = bindSocket(live_sock); + try testing.expect(listening >= 0); + defer _ = libc.close(listening); + try testing.expectEqual(@as(c_int, 0), libc.listen(listening, 1)); + + const starting_lock = claim(starting_sock, &locks[1]) orelse return error.LockFailed; + defer release(starting_lock, std.mem.sliceTo(&locks[1], 0)); + const bound = bindSocket(starting_sock); + try testing.expect(bound >= 0); + defer _ = libc.close(bound); + try testing.expectEqual(@as(c_int, 0), libc.symlink(starting_sock, starting)); + + // Bound and then dropped, its lock let go: the files stay, and nobody + // answers it -- exactly what a killed session leaves behind. + const abandoned = bindSocket(dead_sock); + try testing.expect(abandoned >= 0); + _ = libc.close(abandoned); + const dropped = libc.open(dead_lock, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); + try testing.expect(dropped >= 0); + try testing.expectEqual(@as(c_int, 0), libc.flock(dropped, std.posix.LOCK.EX)); + _ = libc.close(dropped); - /// The walked file's qid: the last walk's, or the root's for none. - fn qid(f: *Flight, root: ninep.Qid) ninep.Qid { - var at = root; - for (f.items[0..f.len]) |item| if (item.step == .walk and item.n > 0) { - at = item.qid; - }; - return at; - } + try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live)); + try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead)); + // Dead too, but its target is not one of our sockets by name, so the + // entry must go and the file it named must survive untouched. + const outside = bindSocket(outsider_sock); + try testing.expect(outside >= 0); + defer _ = libc.close(outside); + try testing.expectEqual(@as(c_int, 0), libc.symlink(outsider_sock, outsider)); + // Not a symlink, so not this program's to reason about, even though + // connecting to it is refused exactly like the dead socket. + try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" }); - /// Whether the walk made the fid, so that it is owed a clunk. - fn made(f: *Flight) bool { - const first = f.get(.walk) orelse return false; - return !first.failed and first.n == first.asked; - } - }; + try testing.expectEqual(Probe.live, probe(live)); + try testing.expectEqual(Probe.stale, probe(dead)); - /// A write in a new connection's first flight is sent before the msize - /// is known: no larger than the least a pardes listener offers. - const flight_write = ninep.min_msize - 23; + sweepRegistry(testing.io, svc, base); - /// Reads ahead this many Treads at once (the window, less a clunk - /// still out and one spare). - const read_ahead = ninep.Client.window - 2; + try testing.expect(statNoFollow(dead) == null); + try testing.expect(statNoFollow(dead_sock) == null); + try testing.expect(statNoFollow(dead_lock) == null); + try testing.expect(statNoFollow(starting) != null); + try testing.expect(statNoFollow(starting_sock) != null); + try testing.expect(statNoFollow(live) != null); + try testing.expect(statNoFollow(live_sock) != null); + try testing.expect(statNoFollow(stranger) != null); + try testing.expect(statNoFollow(outsider) == null); + try testing.expect(statNoFollow(outsider_sock) != null); + try testing.expectEqual(Probe.live, probe(live)); +} - /// Version and attach on a new connection, and a walk to `names`, in - /// one flight: the fid there. - fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !u32 { - var f: Flight = .{}; - try s.greet(&f); - const fid = try s.walkNew(&f, names); - try s.land(&f, null, remote); - f.check(remote) catch |err| { - if (f.made()) s.dropNoWait(fid); - return err; - }; - return fid; - } +test "TCP addresses are numeric and normalize mapped IPv4" { + const loopback = try networkAddress("tcp!127.0.0.1!5640", false); + try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:127.0.0.1!5640", false)); + try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:7f00:1!5640", false)); + try testing.expectEqualDeep(try networkAddress("tcp!::1!5640", false), try networkAddress("tcp!0:0:0:0:0:0:0:1!5640", false)); + try testing.expectEqual(@as(u16, 0), (try networkAddress("tcp!127.0.0.1!0", true)).getPort()); + for ([_][]const u8{ "tcp!localhost!5640", "tcp!127.0.0.1!0", "tcp!127.0.0.1!-1", "tcp!127.0.0.1!65536", "tcp!127.0.0.1!", "tcp!!5640" }) |dial| + try testing.expectError(error.BadDial, networkAddress(dial, false)); + try Client.validateDial("tcp!127.0.0.1!5640"); + try Client.validateDial("/tmp/pardes-owned.sock"); + try Client.validateDial("unix!/tmp/pardes-owned.sock"); + try testing.expectError(error.BadDial, Client.validateDial("unix!work")); + try testing.expectError(error.BadDial, Client.validateDial("nowhere!x")); + try Client.validateDial("/tmp/odd!name.sock"); + try testing.expectError(error.BadDial, Client.validateDial("rel/dir.sock")); + try testing.expectError(error.BadDial, Client.validateDial("unix!")); + try testing.expectError(error.BadDial, Client.validateDial("unix!/tmp/a\x00b")); + try testing.expectError(error.BadDial, Client.validateDial("tcp!localhost!5640")); + try testing.expectError(error.BadDial, Client.validateDial("/tmp/a\x00b")); + try testing.expectError(error.BadDial, Client.validateDial("quic!127.0.0.1!5640")); +} - /// A read's bytes taken in order: a file's as they are, a directory's - /// entries as rows of names. A read ahead that came back out of order, - /// or past one that came back short, is not taken: what it held is - /// read again from where the taken bytes end. - const Taker = struct { - out: *std.Io.Writer.Allocating, - display_path: []const u8, - limit: usize, - /// The flight with the walk, whose answer says what was reached: - /// it lands before any read (a walk never parks). - flight: *Flight, - s: *const Session, - /// Bytes taken from the start; a directory's next offset. - end: u64 = 0, - /// The read that ended at `end` came back short, or empty (the end). - short: bool = false, - empty: bool = false, - /// What taking said (too large, a bad entry): the operation's - /// answer once every read out has landed. - err: ?Error = null, +test "a runtime directory that makes the socket's path pass sun_path is refused in words, the editor running on" { + if (comptime !supported) return error.SkipZigTest; + const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var rt: TempRuntime = .{}; + try rt.init("words"); + defer rt.deinit(); + var buf: [256]u8 = undefined; + try testing.expect(noSocket("x", &buf) == null); + // A directory of 91 bytes (the ledger's was 83, a pid's digits from the + // edge): with a 1-byte name and a pid the socket's path passes sun_path. + var long_buf: [128:0]u8 = undefined; + const long = try std.fmt.bufPrintSentinel(&long_buf, "{s}/{s}", .{ std.mem.sliceTo(&rt.directory, 0), &@as([66]u8, @splat('d')) }, 0); + try testing.expectEqual(@as(usize, 91), long.len); + try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", long, 1)); + const words = noSocket("x", &buf) orelse return error.NotRefused; + try testing.expect(std.mem.startsWith(u8, words, "9p: the socket path is ")); + try testing.expect(std.mem.endsWith(u8, words, " bytes, 108 is the most: set XDG_RUNTIME_DIR shorter")); + // The session's own words, where its pane shows them; no listener. + try testing.expect(start(testing.io, testing.allocator, p) == null); + const pane = p.panes[0].?; + try testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "9p: the socket path is ")); +} - fn take(t: *Taker, item: *Flight.Item, data: []const u8) void { - if (t.err != null or item.off != t.end or t.short) return; - t.put(data) catch |err| { - t.err = err; - return; - }; - t.end += data.len; - t.short = data.len < item.count; - t.empty = data.len == 0; - } +test "a runtime directory open to others is refused in words, never a silent session with no socket" { + if (comptime !supported) return error.SkipZigTest; + const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var rt: TempRuntime = .{}; + try rt.init("open"); + defer rt.deinit(); + // `mkdir -m 700 -p dir/sub` leaves dir itself at the umask's 755. + try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o755)); + var buf: [256]u8 = undefined; + const words = noSocket("x", &buf) orelse return error.NotRefused; + try testing.expect(std.mem.indexOf(u8, words, "must be a directory of yours alone (mode 755") != null); + try testing.expect(start(testing.io, testing.allocator, p) == null); + const pane = p.panes[0].?; + try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "chmod 700 it") != null); + try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o700)); + try testing.expect(noSocket("x", &buf) == null); +} - fn directory(t: *const Taker) bool { - return t.flight.qid(t.s.root_qid).type & ninep.qtdir != 0; - } +test "a socket path too long for sun_path is no listener, and leaves the editor's turn as it was" { + if (comptime !supported) return error.SkipZigTest; + const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var rt: TempRuntime = .{}; + try rt.init("long"); + defer rt.deinit(); + // A name that fits: the directory is one a listener takes. + var fits: [sun_path_len]u8 = undefined; + try testing.expect(socketPath(&fits, std.mem.sliceTo(&rt.directory, 0), "short") != null); + const long = &@as([120]u8, @splat('n')); + try testing.expectError(error.NameTooLong, listen(testing.io, testing.allocator, p, long, "", null)); + try testing.expect(pardes.turn.answer_held == null); + try testing.expect(pardes.turn.wake_parked == null); + try testing.expect(pardes.turn.io == null); +} - fn maxBytes(t: *const Taker) u64 { - return @min(t.limit, @as(usize, if (t.directory()) limits.max_stream_bytes else limits.max_file_bytes)); - } +test "a listening editor posts itself into the 9P registry and unposts on stop" { + if (comptime !supported) return error.SkipZigTest; + const gpa = testing.allocator; + var rt: TempRuntime = .{}; + try rt.init("post"); + defer rt.deinit(); + const dir = std.mem.sliceTo(&rt.directory, 0); - fn wireLimit(t: *const Taker) u64 { - return if (t.directory()) limits.max_stream_bytes else t.maxBytes(); - } + var entry_buf: [sun_path_len:0]u8 = undefined; + const entry = try std.fmt.bufPrintSentinel(&entry_buf, "{s}/9p/pardes/unit", .{dir}, 0); + var sock_buf: [sun_path_len:0]u8 = undefined; + const sock = try std.fmt.bufPrintSentinel(&sock_buf, "{s}/" ++ prefix ++ "unit.sock", .{dir}, 0); - fn put(t: *Taker, data: []const u8) Error!void { - if (t.end + data.len > t.wireLimit()) return Error.FileTooLarge; - if (t.directory()) { - var pos: usize = 0; - while (pos < data.len) { - if (data.len - pos < 2) return Error.Botch; - const len: usize = 2 + @as(usize, std.mem.readInt(u16, data[pos..][0..2], .little)); - if (len > data.len - pos) return Error.Botch; - const entry = ninep.Stat.decode(data[pos..][0..len]) catch return Error.Botch; - const display_dir = std.mem.trimEnd(u8, t.display_path, "/"); - const row_len = display_dir.len + entry.name.len + 2 + @as(usize, @intFromBool(entry.qid.type & ninep.qtdir != 0)); - if (row_len > t.maxBytes() - t.out.written().len) return Error.FileTooLarge; - t.out.writer.print("{s}/{s}", .{ display_dir, entry.name }) catch return Error.Botch; - if (entry.qid.type & ninep.qtdir != 0) t.out.writer.writeByte('/') catch return Error.Botch; - t.out.writer.writeByte('\n') catch return Error.Botch; - pos += len; - } - } else t.out.writer.writeAll(data) catch return Error.Botch; - } - }; + var link: [sun_path_len]u8 = undefined; + { + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const l = try listen(testing.io, gpa, p, "unit", "", null); + defer l.deinit(gpa); + // The socket stays exactly where pardes has always bound it: + // adopting the registry moves nothing, it only advertises. + try testing.expect(statNoFollow(sock) != null); + // It appeared already listening, renamed into place from a name of + // its own, which is gone; its lock held all the while. + try testing.expect(transport.isListening(sock)); + try testing.expectEqual(Probe.live, lockState(sock)); + var tmp_buf: [sun_path_len:0]u8 = undefined; + try testing.expect(statNoFollow(try std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ sock, libc.getpid() }, 0)) == null); + // And the registry holds a symlink to it one directory down, so + // several editors group under /mnt/9p/pardes/ instead of + // crowding the registry root — the layout zmx posts its + // sessions in. + const n = libc.readlink(entry, &link, link.len); + try testing.expect(n > 0); + try testing.expectEqualStrings(sock, link[0..@intCast(n)]); + // A host path no fid names is swept, but never while a request is + // out in a syscall: it may be that request's, mid-walk. + try p.fs.os_paths.append(gpa, .{ .node = @import("fs.zig").os_node | 1, .path = try gpa.dupe(u8, "/tmp") }); + pardes.turn.out = 1; + l.collectOs(); + pardes.turn.out = 0; + try testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); + l.collectOs(); + try testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); + } + // Stopping takes the name back out, so the next editor of that name + // is not refused by its own corpse; the lock goes with the socket. + try testing.expect(libc.readlink(entry, &link, link.len) < 0); + try testing.expectEqual(Probe.none, lockState(sock)); +} + +test "Unix and TCP share one listener through reads writes reconnects and reset" { + if (comptime !supported) return error.SkipZigTest; + const gpa = testing.allocator; + var rt: TempRuntime = .{}; + try rt.init("tcp"); + defer rt.deinit(); + const replacement = try gpa.alloc(u8, 3 * msize + 27); + defer gpa.free(replacement); + @memset(replacement, 'x'); + @memcpy(replacement[0.."changed café λ\n".len], "changed café λ\n"); + replacement[replacement.len - 1] = '\n'; - /// One operation in as few round trips as its answers allow: the walk, - /// a read's stat, the open and the first read or write go in one flight - /// (behind a new connection's version and attach). A file of the - /// length its stat said is whole when a read comes back short at that - /// length; a longer one is read ahead, the Treads for the rest sent at - /// once. Anything else (a directory, a file of no stated length) reads - /// on until a read comes back empty, the only end 9P has. - fn transact( - s: *Session, - names: []const []const u8, - out: *std.Io.Writer.Allocating, - remote: *RemoteError, - write_bytes: ?[]const u8, - read_limit: usize, - ) !void { - const writing = write_bytes != null; - const mode: u8 = if (writing) ninep.owrite else ninep.oread; - const truncate = writing and names.len > 0 and - (std.mem.eql(u8, names[0], "os") or std.mem.eql(u8, names[names.len - 1], "body")); - const fresh = !s.attached; - var f: Flight = .{}; - try s.greet(&f); - const fid = try s.walkNew(&f, names); - if (!writing) _ = f.add(.stat, try s.send(.{ .stat = .{ .fid = fid } })); - _ = f.add(.open, try s.send(.{ .open = .{ .fid = fid, .mode = mode | if (truncate) ninep.otrunc else 0 } })); - const chunk_max: usize = if (fresh) flight_write else s.cl.maxWrite(); - const first: []const u8 = if (write_bytes) |bytes| bytes[0..@min(bytes.len, chunk_max)] else ""; - if (writing and first.len != 0) { - // Out of the client's buffer first (it holds one msize): still - // sent without waiting. - try s.flush(); - _ = f.add(.write, try s.send(.{ .write = .{ .fid = fid, .offset = 0, .data = first } })); - } - // A read's count before the msize is known is the asked msize's. - if (!writing) { - const item = f.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } })); - item.count = s.cl.maxRead(); - } - var taker: Taker = .{ .out = out, .display_path = s.display_path, .limit = read_limit, .flight = &f, .s = s }; - try s.land(&f, &taker, remote); - defer if (f.made()) s.dropNoWait(fid); - try f.check(remote); - if (taker.err) |err| return err; - const directory = taker.directory(); + const Worker = struct { + dial: []const u8, + body_path: []const u8, + expected: []const u8, + replacement: []const u8, + done: std.atomic.Value(bool) = .init(false), + failure: ?anyerror = null, - if (write_bytes) |bytes| { - if (directory) return Error.IsDirectory; - var written: usize = 0; - if (f.get(.write)) |w| { - // Refused unopened, the open parked (a truncating one while - // the editor is out): sent again below, after it. - if (w.failed and !std.mem.eql(u8, w.said.buf[0..w.said.len], ninep.fs.e_bad_use)) return remote.set(w.said.buf[0..w.said.len]); - if (!w.failed) { - if (w.n == 0 or w.n > first.len) return Error.Botch; - written = w.n; - } - } - while (written < bytes.len) { - s.deadline = nowMs() +| write_budget_ms; - const chunk = bytes[written..][0..@min(bytes.len - written, s.cl.maxWrite())]; - const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, remote)).write; - if (count == 0 or count > chunk.len) return Error.Botch; - written += count; - // A long write is timed by its progress: each answer gives - // the next its own budget, so a large body (`pardes -`) goes - // in through one open, whole, however long it takes. The - // budget is a write's: a server putting in tens of MiB it - // held (pane.zig batchFor) answers that one write late. - } - return; + fn run(w: *@This()) void { + defer w.done.store(true, .release); + w.check() catch |err| { + w.failure = err; + }; } - if (f.get(.read)) |r| if (r.failed and !std.mem.eql(u8, r.said.buf[0..r.said.len], ninep.fs.e_bad_use)) - return remote.set(r.said.buf[0..r.said.len]); - const length: u64 = if (f.get(.stat)) |st| (if (st.failed or directory) 0 else st.n) else 0; - const step: u64 = s.cl.maxRead(); - while (true) { - if (taker.empty) return; - if (taker.short and length != 0 and taker.end == length) return; - // The rest of a file of known length at once; a directory, a - // file of none, or the end to be seen, a read at a time. - // ponytail: a file of no stated length is not read ahead. - const want: u64 = if (directory or taker.short or length <= taker.end) 1 else @min(read_ahead, (length - taker.end) / step + 1); - var batch: Flight = .{}; - var off = taker.end; - for (0..want) |_| { - if (off > taker.wireLimit()) break; - const count: u32 = @intCast(@min(step, taker.wireLimit() + 1 - off)); - const item = batch.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = off, .count = count } })); - item.off = off; - item.count = count; - off += count; - } - taker.short = false; - try s.land(&batch, &taker, remote); - if (taker.err) |err| return err; - for (batch.items[0..batch.len]) |item| if (item.failed and item.off == taker.end and !taker.short) - return remote.set(item.said.buf[0..item.said.len]); + fn check(w: *@This()) !void { + const before = try Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len); + defer testing.allocator.free(before); + try testing.expectEqualStrings(w.expected, before); + try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len - 1)); + const listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", 128); + defer testing.allocator.free(listing); + const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len); + defer testing.allocator.free(exact_listing); + try testing.expectEqualStrings(listing, exact_listing); + try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len - 1)); + try Client.write(testing.allocator, w.dial, w.body_path, w.replacement); + const after = try Client.read(testing.allocator, w.dial, w.body_path, w.body_path); + defer testing.allocator.free(after); + try testing.expectEqualStrings(w.replacement, after); + const screen = try Client.read(testing.allocator, w.dial, "/screen", "/screen"); + defer testing.allocator.free(screen); + const parsed = try std.json.parseFromSlice(struct { cols: u16, rows: u16 }, testing.allocator, screen, .{ .ignore_unknown_fields = true }); + defer parsed.deinit(); + try testing.expectEqual(@as(u16, 40), parsed.value.cols); + try testing.expectEqual(@as(u16, 12), parsed.value.rows); } - } + }; - fn fetchBytes( - gpa: std.mem.Allocator, - dial: []const u8, - names: []const []const u8, - remote: *RemoteError, - write_bytes: ?[]const u8, - display_path: []const u8, - read_limit: usize, - keep: bool, - ) ![]u8 { - if (comptime !supported) return Error.Dial; - if (keep) if (kept.take(dial)) |s| { - if (fetchOn(s, gpa, names, remote, write_bytes, read_limit, display_path, true)) |bytes| return bytes else |err| switch (err) { - // Let go of by the peer since (its hangup still on the way): - // a read is asked again on a new connection. A write is not, - // as it may have been done. - error.Hangup, error.Botch => if (write_bytes != null) return err, - else => return err, - } - }; - return fetchOn(try startSession(dial, display_path), gpa, names, remote, write_bytes, read_limit, display_path, keep); + for ([_][]const u8{ "127.0.0.1", "::1" }) |host| { + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("initial\n"); + while (p.nextEffect()) |_| {} + var bind_buf: [64]u8 = undefined; + const bind = try std.fmt.bufPrint(&bind_buf, "tcp!{s}!0", .{host}); + const l = try listen(testing.io, gpa, p, "roundtrip", "", bind); + defer { + l.reset(p); + l.deinit(gpa); + } + try testing.expect(l.path().len != 0); + try testing.expectEqual(@as(usize, max_conns), l.runner.conns.len); + const port = l.tcp_address.?.getPort(); + try testing.expect(port != 0); + var dial_buf: [64]u8 = undefined; + const network_dial = try std.fmt.bufPrint(&dial_buf, "tcp!{s}!{d}", .{ host, port }); + var body_buf: [64]u8 = undefined; + const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); + for ([_][]const u8{ network_dial, l.path(), network_dial }, 0..) |dial, attempt| { + var worker: Worker = .{ .dial = dial, .body_path = body, .expected = if (attempt == 0) "initial\n" else replacement, .replacement = replacement }; + const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); + defer thread.join(); + // The editor rests while the client works: its requests are + // answered on the runner's tasks, not by this thread. + const deadline = nowMs() + 3 * Client.budget_ms; + pardes.turn.rest(); + while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); + // The client has hung up, but its connection's task may not have + // seen that yet. The releases it then owes are refused once + // `reset` starts cutting (they name the old editor's opens), and + // this test's "replacement" is the same editor, so they would + // stay in `p.fs.opens`. Let the hangup pay them first, resting + // so the task can take the turn: that is what is under test here. + const settle_by = nowMs() + 3 * Client.budget_ms; + while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); + pardes.turn.wake(); + try testing.expect(worker.done.load(.acquire)); + if (worker.failure) |err| return err; + try testing.expectEqual(@as(usize, 0), l.runner.count()); + l.reset(p); + try testing.expectEqual(@as(usize, 0), l.runner.count()); + for (p.fs.opens) |o| try testing.expect(o.node == 0); + } } +} - fn fetchOn( - s: *Session, - gpa: std.mem.Allocator, - names: []const []const u8, - remote: *RemoteError, - write_bytes: ?[]const u8, - read_limit: usize, - display_path: []const u8, - keep: bool, - ) ![]u8 { - s.deadline = nowMs() +| budget_ms; - s.display_path = display_path; - var clean = false; - defer endSession(s, keep and clean); - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - transact(s, names, &out, remote, write_bytes, read_limit) catch |err| { - // Refused with every answer in: the connection is as good as before. - clean = switch (err) { - error.Remote, error.NotFound, error.IsDirectory, error.FileTooLarge => true, - else => false, - }; - return err; - }; - clean = true; - return out.toOwnedSlice(); - } +test "a change waits while the editor is out mid-step, a read does not, and the change lands when the editor rests" { + if (comptime !supported) return error.SkipZigTest; + const gpa = testing.allocator; + var rt: TempRuntime = .{}; + try rt.init("park"); + defer rt.deinit(); - /// A new connection at `dial` whose requests have the usual deadline. - fn startSession(dial: []const u8, display_path: []const u8) !*Session { - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); - const deadline = nowMs() +| budget_ms; - // Not the caller's allocator: a kept one outlives the call (an arena's). - const s = try std.heap.page_allocator.create(Session); - s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; - errdefer endSession(s, false); - s.fd = try connect(sock, deadline); - s.cl = .init(.{ .in = &s.in, .out = &s.out }); - if (dial.len <= s.dial_buf.len) { - @memcpy(s.dial_buf[0..dial.len], dial); - s.dial_len = dial.len; - } - return s; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("before\n"); + while (p.nextEffect()) |_| {} + // This thread is the editor's: it has the turn from here on. + const l = try listen(testing.io, gpa, p, "park", "", null); + defer { + l.reset(p); + l.deinit(gpa); } + var body_buf: [64]u8 = undefined; + const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); - fn endSession(s: *Session, keep: bool) void { - if (keep and s.attached and s.dial_len != 0 and kept.put(s)) return; - if (s.fd >= 0) _ = libc.close(s.fd); - std.heap.page_allocator.destroy(s); - } + const Writer = struct { + dial: []const u8, + path: []const u8, + done: std.atomic.Value(bool) = .init(false), + failure: ?anyerror = null, + fn run(w: *@This()) void { + defer w.done.store(true, .release); + Client.write(testing.allocator, w.dial, w.path, "after\n") catch |err| { + w.failure = err; + }; + } + }; + var writer: Writer = .{ .dial = l.path(), .path = body }; - /// Connections kept open between operations, a few dials' (a mount's, - /// as Plan 9's mount keeps its channel): each costs the peer one of its - /// `max_conns` while kept, so only mounts and the Mount probe keep one. - const kept = struct { - const max = 8; - var lock: std.atomic.Mutex = .unlocked; - var slots: [max]?*Session = @splat(null); + // The editor goes out mid-step -- a Look resolving a path, say -- and a + // write arrives meanwhile. It must not land: the step still holds + // pointers into the pane. A read is answered all the same. + pardes.turn.yield(); + const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer}); + defer thread.join(); + nap(150); + try testing.expect(!writer.done.load(.acquire)); + const seen = try Client.readLimit(gpa, l.path(), body, body, 64); + defer gpa.free(seen); + try testing.expectEqualStrings("before\n", seen); + try testing.expect(!writer.done.load(.acquire)); + pardes.turn.back(); + try testing.expectEqualStrings("before\n", pane.file.?.content); - fn hold() void { - while (!lock.tryLock()) std.atomic.spinLoopHint(); - } + // Resting is what lets it in: the parked write is retried, served, and + // the client hears back. + pardes.turn.rest(); + const deadline = nowMs() + Client.budget_ms; + while (!writer.done.load(.acquire) and nowMs() < deadline) nap(1); + pardes.turn.wake(); + try testing.expect(writer.done.load(.acquire)); + if (writer.failure) |err| return err; + // Its bytes are held until its open is let go (pane.zig `batchFor`), and + // the client lets it go without waiting: rested again until that lands, + // the body read only while the editor has the turn. + while (!std.mem.eql(u8, pane.file.?.content, "after\n") and nowMs() < deadline) { + pardes.turn.rest(); + nap(1); + pardes.turn.wake(); + } + try testing.expectEqualStrings("after\n", pane.file.?.content); +} - /// The session kept for `dial`, out of the table, if it is still - /// there: what came while it waited (a clunk's answer) taken, and - /// a hangup or anything else seen as its end. - fn take(dial: []const u8) ?*Session { - hold(); - const s = for (&slots) |*slot| { - const got = slot.* orelse continue; - if (std.mem.eql(u8, got.dial_buf[0..got.dial_len], dial)) { - slot.* = null; - break got; - } - } else null; - lock.unlock(); - const found = s orelse return null; - if (usable(found)) return found; - endSession(found, false); - return null; - } +test "a mount's connection is kept between operations, and one the peer hung up is dialled again" { + if (comptime !supported) return error.SkipZigTest; + const gpa = testing.allocator; + var rt: TempRuntime = .{}; + try rt.init("kept"); + defer rt.deinit(); - fn usable(s: *Session) bool { - while (true) { - var fds = [1]libc.pollfd{.{ .fd = s.fd, .events = poll_in, .revents = 0 }}; - if (libc.poll(&fds, 1, 0) < 0) return false; - if (fds[0].revents == 0) return true; - if (fds[0].revents & poll_in == 0) return false; - const room = s.cl.in.len - s.cl.in_len; - if (room == 0) return false; - const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return false) orelse return true; - if (got == 0) return false; - _ = s.cl.push(s.stage[0..got]); - while (s.cl.take()) |done| { - if (done.tag >= 32 or s.unwaited & bit(done.tag) == 0) return false; - s.unwaited &= ~bit(done.tag); - } - if (s.cl.dead) return false; - } - } + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("before\n"); + while (p.nextEffect()) |_| {} + const l = try listen(testing.io, gpa, p, "kept", "", null); + defer { + l.reset(p); + l.deinit(gpa); + } + var body_buf: [64]u8 = undefined; + const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial}); + const long = try gpa.alloc(u8, 2 * msize + 5); + defer gpa.free(long); + @memset(long, 'k'); + long[long.len - 1] = '\n'; - fn put(s: *Session) bool { - hold(); - defer lock.unlock(); - for (&slots) |*slot| if (slot.* == null) { - slot.* = s; - return true; + const Worker = struct { + l: *Listener, + body: []const u8, + long: []const u8, + done: std.atomic.Value(bool) = .init(false), + failure: ?anyerror = null, + fn run(w: *@This()) void { + defer w.done.store(true, .release); + w.check() catch |err| { + w.failure = err; }; - return false; + } + fn read(w: *@This(), want: []const u8) !void { + const got = try Client.readMount(testing.allocator, w.l.path(), w.body, w.body, limits.max_file_bytes); + defer testing.allocator.free(got); + try testing.expectEqualStrings(want, got); + } + fn check(w: *@This()) !void { + defer Client.forget(w.l.path()); + try w.read("before\n"); + try w.read("before\n"); + // A write longer than a message, and a miss, on the same one. + try Client.writeMount(testing.allocator, w.l.path(), w.body, w.long); + try w.read(w.long); + try testing.expectError(error.NotFound, Client.readMount(testing.allocator, w.l.path(), "/pane/no-such", "/pane/no-such", 64)); + try testing.expectEqual(@as(u64, 1), w.l.accepts.load(.acquire)); + // The peer hangs up (a Restore cuts its clients): the next + // operation dials again and is answered. + for (&w.l.runner.conns) |*conn| if (conn.live()) conn.close(); + const by = nowMs() + Client.budget_ms; + while (w.l.runner.count() != 0 and nowMs() < by) nap(1); + try w.read(w.long); + try testing.expectEqual(@as(u64, 2), w.l.accepts.load(.acquire)); } }; + var worker: Worker = .{ .l = l, .body = body, .long = long }; + pardes.turn.rest(); + const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); + const deadline = nowMs() + 3 * Client.budget_ms; + while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); + thread.join(); + // Forgotten: the kept connection is closed, and its task sees it. + const settle_by = nowMs() + Client.budget_ms; + while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); + pardes.turn.wake(); + if (worker.failure) |err| return err; + try testing.expectEqual(@as(usize, 0), l.runner.count()); +} - /// Lets go of a connection kept for `dial` (an Unmount): its mount is gone. - pub fn forget(dial: []const u8) void { - if (comptime !supported) return; - while (kept.take(dial)) |s| endSession(s, false); - } +test "a connection holds up to 128 reads, and the next is refused in words" { + try testing.expectEqual(@as(usize, 128), ninep.max_held); + if (comptime supported) try testing.expectEqualStrings("too many reads waiting: 128", Runner.Engine.e_waiting); +} - /// Writes `request`, then `more`, to `path` and reads the answer on the - /// same open, as /pane/new answers its own open: a session's last - /// answer, from another client, can never be what comes back. `exec - /// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in - /// Twrites at rising offsets, each answer giving the next its budget. - pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 { - if (comptime !supported) return error.Unsupported; - var names: [max_depth][]const u8 = undefined; - const n = try elements(path, &names); - var remote: RemoteError = .{}; - errdefer said = remote; - const s = try startSession(dial, path); - defer endSession(s, false); - const fid = try walkTo(s, names[0..n], &remote); - _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); - var written: usize = 0; - while (written < request.len + more.len) { - const from = if (written < request.len) request[written..] else more[written - request.len ..]; - const chunk = from[0..@min(from.len, s.cl.maxWrite())]; - const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write; - if (count == 0 or count > chunk.len) return Error.Botch; - written += count; - s.deadline = nowMs() +| write_budget_ms; - } - var out: std.ArrayList(u8) = .empty; - errdefer out.deinit(gpa); - while (true) { - const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = out.items.len, .count = s.cl.maxRead() } }, &remote)).read; - if (data.len == 0) return out.toOwnedSlice(gpa); - if (out.items.len + data.len > 4096) return Error.FileTooLarge; - try out.appendSlice(gpa, data); - } - } +test "a held read is answered when the log has news, and a flushed one spends nothing" { + if (comptime !supported) return error.SkipZigTest; + const gpa = testing.allocator; + var rt: TempRuntime = .{}; + try rt.init("held"); + defer rt.deinit(); - /// Opens `path` on one connection and writes `first` to it (/log's - /// `follow new`), all with the usual deadline; then, once `ready(ctx)` - /// has said it is not done already, reads it with no deadline, a read at - /// a time, until `record(ctx, bytes)` says done. An end of file or a - /// dropped connection is Hangup. What `pardes --wait` blocks on. - pub fn follow( - dial: []const u8, - path: []const u8, - first: []const u8, - ctx: anytype, - comptime ready: fn (@TypeOf(ctx)) bool, - comptime record: fn (@TypeOf(ctx), []const u8) bool, - ) !void { - if (comptime !supported) return error.Unsupported; - var names: [max_depth][]const u8 = undefined; - const n = try elements(path, &names); - var remote: RemoteError = .{}; - const s = try startSession(dial, path); - defer endSession(s, false); - const fid = try walkTo(s, names[0..n], &remote); - _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); - _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); - if (ready(ctx)) return; - s.deadline = std.math.maxInt(i64); - while (true) { - const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } }, &remote)).read; - if (data.len == 0) return Error.Hangup; - if (record(ctx, data)) return; - } + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + _ = try p.setTestFile("held\n"); + p.update(.tick); // the pane is logged, before the log is opened + while (p.nextEffect()) |_| {} + const l = try listen(testing.io, gpa, p, "held", "", null); + defer { + l.reset(p); + l.deinit(gpa); } - - fn connect(sock: Dial, deadline: i64) Error!c_int { - const address: transport.Address = switch (sock) { - .unix => |path| .{ .unix = path }, - .tcp => |ip| .{ .tcp = ip }, - }; - return transport.connectFd(address, deadline) catch return Error.Dial; + // This thread is the editor's and plays the client too, resting while + // it does so that the runner's tasks can take the turn and answer. + const s = try gpa.create(Client.Session); + defer gpa.destroy(s); + s.* = .{ .fd = -1, .deadline = nowMs() + 3 * Client.budget_ms, .display_path = "/log" }; + var sock_buf: [sun_path_len]u8 = undefined; + pardes.turn.rest(); + defer pardes.turn.wake(); + s.fd = try Client.connect(try Client.resolve(&sock_buf, l.path()), s.deadline); + defer _ = libc.close(s.fd); + s.cl = .init(.{ .in = &s.in, .out = &s.out }); + var remote: Client.RemoteError = .{}; + _ = try s.ask(.{ .version = .{} }, &remote); + _ = try s.ask(.{ .attach = .{ .fid = 0, .uname = "held" } }, &remote); + _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"log"} } }, &remote); + _ = try s.ask(.{ .open = .{ .fid = 1, .mode = ninep.ordwr } }, &remote); + var frozen: u64 = 0; + while (true) { + const n = (try s.ask(.{ .read = .{ .fid = 1, .offset = frozen, .count = 4096 } }, &remote)).read.len; + if (n == 0) break; + frozen += n; } + _ = try s.ask(.{ .write = .{ .fid = 1, .offset = 0, .data = "follow\n" } }, &remote); - const poll_in: i16 = @intCast(libc.POLL.IN); - const poll_out: i16 = @intCast(libc.POLL.OUT); + const heldNow = struct { + /// Waits until the core holds `n` reads. + fn count(core: *pardes.Pardes, n: usize) !void { + const deadline = nowMs() + Client.budget_ms; + while (nowMs() < deadline) { + pardes.turn.wake(); + var got: usize = 0; + for (core.fs.opens) |o| got += @intFromBool(o.held != null); + pardes.turn.rest(); + if (got == n) return; + nap(1); + } + return error.Timeout; + } + }; + const serial = p.panes[0].?.serial; + var event_path: [32]u8 = undefined; + var event_names: [3][]const u8 = .{ "pane", try std.fmt.bufPrint(&event_path, "{d}", .{serial}), "event" }; + _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 2, .names = &event_names } }, &remote); + _ = try s.ask(.{ .open = .{ .fid = 2, .mode = ninep.oread } }, &remote); - test "a path becomes walk elements, normalised the way a shell would" { - var out: [max_depth][]const u8 = undefined; - try testing.expectEqual(@as(usize, 3), try elements("/pane/1/body", &out)); - try testing.expectEqualStrings("pane", out[0]); - try testing.expectEqualStrings("1", out[1]); - try testing.expectEqualStrings("body", out[2]); + // Flushed while held, a read is gone from the engine without the core + // hearing of it. Its tag, asked again at once for a read of the pane's + // event, must not be answered with the log's next record, and that + // record must reach the log's next read. + const flushed = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.count(p, 1); + _ = try s.cl.submit(.{ .flush = .{ .oldtag = flushed } }); + const interrupted = try s.settle(); + try testing.expectEqual(flushed, interrupted.tag); + try testing.expect(interrupted.result == .fail); + try testing.expect((try s.settle()).result == .flush); + const reused = try s.cl.submit(.{ .read = .{ .fid = 2, .offset = 0, .count = 4096 } }); + try testing.expectEqual(flushed, reused); + try s.flush(); + try heldNow.count(p, 2); + pardes.turn.wake(); + p.setMessage(0, "after the flush"); + pardes.turn.rest(); + try heldNow.count(p, 1); + pardes.turn.wake(); + p.fs.origin = 'K'; + pardes.ctlfs.events.noteAction(p, 0, .body_exec, 0, 4, 0, "held"); + pardes.turn.rest(); + const clicked = try s.settle(); + try testing.expectEqual(reused, clicked.tag); + try testing.expectEqualStrings("KX0 4 0 4 held\n", clicked.result.read); + try testing.expect(std.mem.indexOf(u8, (try s.ask(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }, &remote)).read, "after the flush") != null); - try testing.expectEqual(@as(usize, 3), try elements("pane/1/body", &out)); - try testing.expectEqual(@as(usize, 3), try elements("//pane//1//body//", &out)); - try testing.expectEqual(@as(usize, 1), try elements("/index", &out)); + // Held, a read is answered by the record that arrives, on its own + // connection, with no retry of every parked request asked for; a + // second read on the same open meanwhile is refused, not orphaned. + const waiting = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.count(p, 1); + const second = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + const refused = try s.settle(); + try testing.expectEqual(second, refused.tag); + try testing.expectEqualStrings(pardes.ctlfs.e_in_use, refused.result.fail); + pardes.turn.wake(); + p.setMessage(0, "while held"); + const retry_all = pardes.turn.parked; + pardes.turn.rest(); + try testing.expect(!retry_all); + const answered = try s.settle(); + try testing.expectEqual(waiting, answered.tag); + try testing.expect(std.mem.indexOf(u8, answered.result.read, "while held") != null); - try testing.expectEqual(@as(usize, 0), try elements("/", &out)); + // Clunked, the log's held read is interrupted by the engine and the + // record it would have had is spent on nobody. + _ = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.count(p, 1); + s.drop(1); + s.drop(2); + try heldNow.count(p, 0); - var deep: [8 * max_depth]u8 = @splat('/'); - for (0..max_depth + 1) |i| deep[i * 2 + 1] = 'a'; - try testing.expectError(Error.PathTooDeep, elements(deep[0 .. (max_depth + 1) * 2], &out)); + // Records queued as a Restore comes reach a follower in the answer to + // the read it holds, all of them, before the hangup cuts it. (The + // interrupted read above answered first: one clunk's answer is unread.) + _ = try s.settle(); + _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 3, .names = &.{"log"} } }, &remote); + _ = try s.ask(.{ .open = .{ .fid = 3, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = 3, .offset = 0, .data = "follow new\n" } }, &remote); + const last = try s.cl.submit(.{ .read = .{ .fid = 3, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.count(p, 1); + pardes.turn.wake(); + p.setMessage(0, "queued one"); + p.setMessage(0, "queued two"); + p.setMessage(0, "queued three"); + l.reset(p); + pardes.turn.rest(); + const cut = try s.settle(); + try testing.expectEqual(last, cut.tag); + for ([_][]const u8{ "queued one", "queued two", "queued three" }) |said| + try testing.expect(std.mem.indexOf(u8, cut.result.read, said) != null); +} + +test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" { + const names = [_][*:0]const u8{ "NINE_MNTGEN", "NINE_MOUNT", "PARDES_MOUNT" }; + var saved: [names.len]?[:0]u8 = @splat(null); + for (names, &saved) |name, *value| { + if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); } + defer for (names, saved) |name, value| { + if (value) |old| { + _ = setenv(name, old, 1); + testing.allocator.free(old); + } else _ = @import("host_io.zig").testUnsetenv(name); + }; + _ = setenv("NINE_MOUNT", "/mnt/9p", 1); + _ = setenv("NINE_MNTGEN", "1", 1); + exportMount("/run/user/1000/pardes-9p-work.sock"); + try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?); + // A mount of another server (9ns --unix): not this session's. + _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN"); + exportMount("/run/user/1000/pardes-9p-work.sock"); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null); +} - test "a bare dial resolves to the socket --9p binds, and a path is taken as given" { - if (comptime !supported) return error.SkipZigTest; - var buf: [sun_path_len]u8 = undefined; +test "9P shell environment states being inside pardes apart from how to reach it" { + const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" }; + var saved: [names.len]?[:0]u8 = @splat(null); + for (names, &saved) |name, *value| { + if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0); + } + defer for (names, saved) |name, value| { + if (value) |old| { + _ = setenv(name, old, 1); + testing.allocator.free(old); + } else _ = @import("host_io.zig").testUnsetenv(name); + }; - const named = (try resolve(&buf, "work")).unix; - try testing.expect(std.mem.endsWith(u8, named, "/pardes-9p-work.sock")); - var expect: [sun_path_len]u8 = undefined; - var dir_buf: [sun_path_len:0]u8 = undefined; - const dir = socketDir(&dir_buf).?; - try testing.expectEqualStrings(socketPath(&expect, dir, "work").?, named); + var dir: [sun_path_len:0]u8 = undefined; + _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1); + try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); + _ = setenv("HOME", "/home/example", 1); + try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); + _ = @import("host_io.zig").testUnsetenv("HOME"); + try testing.expect(socketDir(&dir) == null); - const path = (try resolve(&buf, "/tmp/somewhere.sock")).unix; - try testing.expectEqualStrings("/tmp/somewhere.sock", path); - try testing.expectEqualStrings("/tmp/somewhere.sock", (try resolve(&buf, "unix!/tmp/somewhere.sock")).unix); + // The socket a listener keeps while it lives. + const path = "/tmp/pardes-example.sock"; + @memcpy(own_socket[0..path.len], path); + own_socket[path.len] = 0; + own_socket_len = path.len; + defer own_socket_len = 0; + var own: [16]u8 = undefined; + const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))}); - try testing.expectError(error.BadDial, resolve(&buf, "")); - try testing.expectError(error.BadDial, resolve(&buf, "/tmp/a\x00b")); - } + // A `--nested` session: reachable for scripts and mounts, but nobody's + // parent, so a pardes started in one of its shells runs a session of + // its own instead of handing its argument over. + exportEnv(7, false); + try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?); + try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); - test "a dial with nothing listening is one error and not a wait" { - if (comptime !supported) return error.SkipZigTest; - var names: [max_depth][]const u8 = undefined; - const n = try elements("/pane/1/body", &names); - var remote: RemoteError = .{}; - const before = nowMs(); - try testing.expectError( - Error.Dial, - fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes, false), - ); - try testing.expect(nowMs() - before < budget_ms); - } + exportEnv(8, true); + try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); - test "one fetch has three msize buffers and bounded transport metadata" { - try testing.expectEqual(@as(usize, msize), @as(usize, (Session{ .fd = -1, .deadline = 0, .display_path = "" }).in.len)); - try testing.expect(@sizeOf(Session) <= 3 * msize + @sizeOf(ninep.Client) + 128 + @sizeOf(@FieldType(Session, "dial_buf"))); - try testing.expect(@sizeOf(ninep.Client) <= 512); - } + // A session whose listener never came up is still the session this shell + // is inside: the pid stands on its own, and only the address is missing. + own_socket_len = 0; + exportEnv(0, true); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); - test "expired sessions do not send or consume buffered protocol work" { - var session: Session = .{ .fd = -1, .deadline = 0, .display_path = "" }; - session.cl = .init(.{ .in = &session.in, .out = &session.out }); - _ = try session.cl.submit(.{ .version = .{} }); - const queued = session.cl.output().len; - try testing.expect(queued > 0); - try testing.expectError(Error.Timeout, session.flush()); - try testing.expectEqual(queued, session.cl.output().len); - try testing.expectError(Error.Timeout, session.settle()); - try testing.expectError(Error.Timeout, session.wait(poll_in)); - } -}; + exportEnv(0, false); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); +} diff --git a/src/Art.zig b/src/Art.zig index 6a938f68..6cc33e2e 100644 --- a/src/Art.zig +++ b/src/Art.zig @@ -466,6 +466,34 @@ fn renderRect(gpa: std.mem.Allocator, raster: Raster, src: RectPx, cols: usize, return .{ .cells = cells, .cols = cols, .rows = rows }; } +pub const terminal_palette = [16][3]u8{ + .{ 0x1D, 0x1F, 0x21 }, // black + .{ 0xCC, 0x66, 0x66 }, // red + .{ 0xB5, 0xBD, 0x68 }, // green + .{ 0xF0, 0xC6, 0x74 }, // yellow + .{ 0x81, 0xA2, 0xBE }, // blue + .{ 0xB2, 0x94, 0xBB }, // magenta + .{ 0x8A, 0xBE, 0xB7 }, // cyan + .{ 0xC5, 0xC8, 0xC6 }, // white + .{ 0x66, 0x66, 0x66 }, // bright black + .{ 0xD5, 0x4E, 0x53 }, // bright red + .{ 0xB9, 0xCA, 0x4A }, // bright green + .{ 0xE7, 0xC5, 0x47 }, // bright yellow + .{ 0x7A, 0xA6, 0xDA }, // bright blue + .{ 0xC3, 0x97, 0xD8 }, // bright magenta + .{ 0x70, 0xC0, 0xB1 }, // bright cyan + .{ 0xEA, 0xEA, 0xEA }, // bright white +}; + +comptime { + for (terminal_palette, 0..) |rgb, i| { + const c = ghostty_vt.color.default[i]; + if (rgb[0] != c.r or rgb[1] != c.g or rgb[2] != c.b) @compileError( + "terminal palette differs from the emulator", + ); + } +} + test "sextant codepoints: blocks + endpoints" { try std.testing.expectEqual(@as(u21, ' '), sextantCp(0)); try std.testing.expectEqual(@as(u21, 0x2588), sextantCp(63)); @@ -543,33 +571,6 @@ test "a tiny image fitted into cells makes a grid within bounds" { try std.testing.expect(g.rows >= 1 and g.rows <= 10); try std.testing.expectEqual(g.cols * g.rows, g.cells.len); } -pub const terminal_palette = [16][3]u8{ - .{ 0x1D, 0x1F, 0x21 }, // black - .{ 0xCC, 0x66, 0x66 }, // red - .{ 0xB5, 0xBD, 0x68 }, // green - .{ 0xF0, 0xC6, 0x74 }, // yellow - .{ 0x81, 0xA2, 0xBE }, // blue - .{ 0xB2, 0x94, 0xBB }, // magenta - .{ 0x8A, 0xBE, 0xB7 }, // cyan - .{ 0xC5, 0xC8, 0xC6 }, // white - .{ 0x66, 0x66, 0x66 }, // bright black - .{ 0xD5, 0x4E, 0x53 }, // bright red - .{ 0xB9, 0xCA, 0x4A }, // bright green - .{ 0xE7, 0xC5, 0x47 }, // bright yellow - .{ 0x7A, 0xA6, 0xDA }, // bright blue - .{ 0xC3, 0x97, 0xD8 }, // bright magenta - .{ 0x70, 0xC0, 0xB1 }, // bright cyan - .{ 0xEA, 0xEA, 0xEA }, // bright white -}; - -comptime { - for (terminal_palette, 0..) |rgb, i| { - const c = ghostty_vt.color.default[i]; - if (rgb[0] != c.r or rgb[1] != c.g or rgb[2] != c.b) @compileError( - "terminal palette differs from the emulator", - ); - } -} test "a frontend draws a placement as glyph art where it shows no pixels, or where its pane asks, and else leaves the frame be" { const gpa = std.testing.allocator; diff --git a/src/Db.zig b/src/Db.zig index 73e6480a..f7966ee0 100644 --- a/src/Db.zig +++ b/src/Db.zig @@ -95,40 +95,6 @@ pub fn statePath(buf: []u8, dir_setting: []const u8) ?[]const u8 { return std.fmt.bufPrint(buf, "{s}/" ++ file_name, .{dir}) catch null; } -/// The database, opened (made, when its file is not there) at its first use -/// and again once the DumpDir names another: null when this session keeps -/// none, or it cannot be had now (the next use tries again). -fn opened(db: *Db, p: *Pardes) ?*Open { - switch (db.kind) { - .off => return null, - .disk => { - var buf: [4200]u8 = undefined; - const path = statePath(&buf, p.settings.dump_dir.get()) orelse return null; - if (db.open) |o| { - // The same file still: another session's compaction renames - // a new one over it, which this one then opens. - if (std.mem.eql(u8, o.where.disk.path, path) and !replaced(o)) return o; - // The DumpDir moved: its own file, read afresh. - db.deinit(); - db.seen = 0; - } - db.open = openDisk(p.recentGpa(), path) catch return null; - }, - .memory => if (db.open == null) { - const gpa = p.recentGpa(); - const o = gpa.create(Open) catch return null; - o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined }; - o.where = .{ .memory = .{ .db = Memory.init(ioOf(), .{ .buffer = &o.buffer, .hash_id = hash_id }) catch { - o.buffer.deinit(); - gpa.destroy(o); - return null; - } } }; - db.open = o; - }, - } - return db.open; -} - /// The state file at `path`, its directory made: a new one is written under /// the file's lock (two sessions starting at once write one header), one a /// power loss tore is opened at its last whole commit (`mend`), and a file @@ -1140,6 +1106,40 @@ pub const Cache = struct { const testing = std.testing; +/// The database, opened (made, when its file is not there) at its first use +/// and again once the DumpDir names another: null when this session keeps +/// none, or it cannot be had now (the next use tries again). +fn opened(db: *Db, p: *Pardes) ?*Open { + switch (db.kind) { + .off => return null, + .disk => { + var buf: [4200]u8 = undefined; + const path = statePath(&buf, p.settings.dump_dir.get()) orelse return null; + if (db.open) |o| { + // The same file still: another session's compaction renames + // a new one over it, which this one then opens. + if (std.mem.eql(u8, o.where.disk.path, path) and !replaced(o)) return o; + // The DumpDir moved: its own file, read afresh. + db.deinit(); + db.seen = 0; + } + db.open = openDisk(p.recentGpa(), path) catch return null; + }, + .memory => if (db.open == null) { + const gpa = p.recentGpa(); + const o = gpa.create(Open) catch return null; + o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined }; + o.where = .{ .memory = .{ .db = Memory.init(ioOf(), .{ .buffer = &o.buffer, .hash_id = hash_id }) catch { + o.buffer.deinit(); + gpa.destroy(o); + return null; + } } }; + db.open = o; + }, + } + return db.open; +} + /// A window keeping its state in `dir` (never the user's DumpDir). fn testWindow(dir: []const u8) !*Pardes { var config: [4200]u8 = undefined; diff --git a/src/File.zig b/src/File.zig index 553f34e4..d5438704 100644 --- a/src/File.zig +++ b/src/File.zig @@ -233,15 +233,6 @@ pub fn graphemeDisplayWidth(grapheme: []const u8) usize { return @max(1, width); } -test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" { - try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81")); - try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe")); - try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80")); - // The whole path the 9P fuzzer took: a body holding it, fitted to a width. - const text = "\xeee\xcc\x81"; - try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); -} - pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -323,36 +314,6 @@ pub fn sourceLine(pane: *const Pane, row: i32) []const u8 { return f.content[start..end]; } -test "indexed source rows match uncached scans across content changes" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile(""); - const file = &pane.file.?; - for ([_][]const u8{ "", "one", "one\n", "a\r\nλ界\nlast", "\n\n", "\tλ e\u{301}\n\r\n" }) |content| { - setContent(p, file, try p.gpa.dupe(u8, content)); - // An edit carries a built index forward; it must equal a fresh one. - if (file.line_starts.len > 0) { - const carried = file.line_starts; - const room = indexRoom(file); - defer p.gpa.free(room); - file.line_starts = &.{}; - try std.testing.expectEqualSlices(usize, try lineIndex(p.gpa, file), carried); - p.gpa.free(file.line_starts); - file.line_starts = &.{}; - } - const rows = lineCount(content) + 2; - for ([_]bool{ false, true }) |indexed| { - if (indexed) _ = try lineIndex(p.gpa, file); - try std.testing.expectEqualStrings("", sourceLine(pane, -1)); - for (0..rows) |row| try std.testing.expectEqualStrings( - modal.lineSlice(content, row), - sourceLine(pane, @intCast(row)), - ); - if (!indexed) try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); - } - } -} - /// The pads `row` is laid out with in this pane: a row of a markdown /// table (Tables.zig) of its text as it is now, when the table fits the /// width a wrapping body has (a wider one is shown as its source, wrapped); @@ -430,82 +391,6 @@ pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8 return prefix +| rawDisplayCol(line_text[prefix..], byte_col - prefix); } -test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { - const ref = struct { - fn width(grapheme: []const u8) usize { - if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; - return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); - } - }.width; - - var one: [1]u8 = undefined; - var b: u8 = 0; - while (b < 0x80) : (b += 1) { - one[0] = b; - try std.testing.expectEqual(ref(one[0..1]), graphemeDisplayWidth(one[0..1])); - } - for ([_][]const u8{ - "e\u{301}", "a\u{903}", "1\u{fe0f}\u{20e3}", "\u{4e16}", - "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", - }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); - // Two invalid bytes are two cells, as surface.zig draws them, where - // vaxis's own count gives the pair one. - try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8")); -} - -test "the ASCII run in fitEnd survives an exhaustive byte sweep" { - const reference = struct { - fn fitEnd(text: []const u8, start: usize, width: usize) usize { - var end = start; - var used: usize = 0; - while (end < text.len) { - const next_end = modal.nextGrapheme(text, end); - const next_used = used +| graphemeDisplayWidth(text[end..next_end]); - if (next_used > width) return if (end == start) next_end else end; - used = next_used; - end = next_end; - } - return end; - } - }.fitEnd; - - const neighbours = [_][]const u8{ - "", "z", "\u{301}", "\u{200d}\u{1f680}", - "\u{903}", "\u{fe0f}", "\u{4e16}", "\u{1f642}", - "\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", - }; - var buf: [16]u8 = undefined; - // The same pair again behind an ASCII prefix, so a break can land exactly at the run boundary - // as well as before it and inside the multi-byte cluster that follows it. - var prefixed: [18]u8 = undefined; - prefixed[0] = 'a'; - prefixed[1] = 'b'; - var b: u8 = 0; - while (b < 0x80) : (b += 1) { - buf[0] = b; - for (neighbours) |tail| { - @memcpy(buf[1..][0..tail.len], tail); - const pair = buf[0 .. 1 + tail.len]; - @memcpy(prefixed[2..][0..pair.len], pair); - for ([_][]const u8{ pair, prefixed[0 .. 2 + pair.len] }) |text| { - var width: usize = 0; - while (width <= text.len + 3) : (width += 1) { - var start: usize = 0; - while (start <= text.len) : (start += 1) { - std.testing.expectEqual( - reference(text, start, width), - fitEnd(text, start, width), - ) catch |e| { - std.debug.print("fitEnd({any}, {d}, {d})\n", .{ text, start, width }); - return e; - }; - } - } - } - } - } -} - fn fitEnd(text: []const u8, start: usize, width: usize) usize { var end = start; var used: usize = 0; @@ -526,52 +411,6 @@ fn fitEnd(text: []const u8, start: usize, width: usize) usize { return end; } -test "the ASCII run in fitEnd cuts where the grapheme walk would" { - const reference = struct { - fn fitEnd(text: []const u8, start: usize, width: usize) usize { - var end = start; - var used: usize = 0; - while (end < text.len) { - const next_end = modal.nextGrapheme(text, end); - const next_used = used +| graphemeDisplayWidth(text[end..next_end]); - if (next_used > width) return if (end == start) next_end else end; - used = next_used; - end = next_end; - } - return end; - } - }.fitEnd; - - const cases = [_][]const u8{ - "", - "hello world", - // the fast path must hand over at the first non-ASCII byte, mid-run - "abc\u{00e9}def", - // a wide glyph is two columns, so a width boundary can land inside it - "ab\u{4e16}\u{754c}cd", - // a cluster the fast path must not split - "a\u{0301}bc", - // tabs and controls are excluded from the fast path by the range test - "ab\tcd", - "ab\rcd", - // an ASCII byte followed by a continuation byte is NOT its own cluster - "e\u{0301}x", - "\u{1f1e6}\u{1f1e7}ok", - }; - for (cases) |text| { - var width: usize = 0; - while (width <= text.len + 3) : (width += 1) { - var start: usize = 0; - while (start <= text.len) : (start += 1) { - try std.testing.expectEqual( - reference(text, start, width), - fitEnd(text, start, width), - ); - } - } - } -} - pub const lineCount = modal.cursorLineCount; // Content changes invalidate this lazily rebuilt byte-offset index. @@ -668,44 +507,6 @@ pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, } } -test "a line index shifted in place equals a rebuilt one, and the edit turned round gives the one before back" { - const gpa = std.testing.allocator; - var prng = std.Random.DefaultPrng.init(11); - const r = prng.random(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..300) |_| try text.append(gpa, "ab\n"[r.uintLessThan(usize, 3)]); - var f: State = .{ .path = &.{}, .content = text.items, .history = undefined }; - _ = try lineIndex(gpa, &f); - defer gpa.free(indexRoom(&f)); - for (0..2000) |round| { - const at = r.uintAtMost(usize, text.items.len); - const del = r.uintAtMost(usize, @min(12, text.items.len - at)); - var ins: [12]u8 = undefined; - const ins_len = r.uintAtMost(usize, 12); - for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; - const before = try gpa.dupe(usize, f.line_starts); - defer gpa.free(before); - const cut = try gpa.dupe(u8, text.items[at..][0..del]); - defer gpa.free(cut); - f.content = text.items; - shiftIndex(gpa, &f, at, del, ins[0..ins_len]); - try text.replaceRange(gpa, at, del, ins[0..ins_len]); - var fresh: State = .{ .path = &.{}, .content = text.items, .history = undefined }; - const want = try lineIndex(gpa, &fresh); - defer gpa.free(want); - try std.testing.expectEqualSlices(usize, want, f.line_starts); - // Every tenth turned round in a copy, as a rollback takes it back. - if (round % 10 == 0) { - const room = try gpa.alloc(usize, indexRoom(&f).len); - defer gpa.free(room); - @memcpy(room[0..f.line_starts.len], f.line_starts); - shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); - try std.testing.expectEqualSlices(usize, before, room[0..before.len]); - } - } -} - /// line count, O(1) once the index is warm pub fn nlines(gpa: std.mem.Allocator, f: *State) usize { const idx = lineIndex(gpa, f) catch return lineCount(f.content); @@ -760,28 +561,6 @@ pub fn textLine(t: *Text, text: []const u8, row: usize) []const u8 { return text[start..end]; } -test "indexed text rows preserve fragment and allocation failure semantics" { - var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("first\n\tλ界\n\nlast\n"); - const text = pane.file.?.content; - allocator.fail_index = allocator.alloc_index; - for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(&pane.body, text, row)); - try std.testing.expectEqual(@as(usize, 0), pane.file.?.line_starts.len); - allocator.fail_index = std.math.maxInt(usize); - _ = try lineIndex(p.gpa, &pane.file.?); - allocator.fail_index = allocator.alloc_index; - const allocations = allocator.allocations; - for ([_][]const u8{ text, text[2..], text[0..8], "other\nrows\n\n", "" }) |fragment| { - for (0..lineCount(fragment) + 2) |row| try std.testing.expectEqualStrings( - modal.lineSlice(fragment, row), - textLine(&pane.body, fragment, row), - ); - } - try std.testing.expectEqual(allocations, allocator.allocations); -} - pub fn textLineCount(t: *Text, text: []const u8) usize { const index = contentIndex(t, text) orelse return modal.cursorLineCount(text); return index.len; @@ -1131,29 +910,6 @@ pub fn spanOf(old: []const u8, new: []const u8) Span { return .{ .head = head, .tail = tail }; } -test "spanOf by blocks finds the byte loop's ends" { - var prng: std.Random.DefaultPrng = .init(5); - const random = prng.random(); - var a: [160]u8 = undefined; - var b: [160]u8 = undefined; - for (0..4000) |_| { - const la = random.uintLessThan(usize, a.len); - const lb = random.uintLessThan(usize, b.len); - for (a[0..la]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; - const keep = @min(la, lb); - @memcpy(b[0..keep], a[0..keep]); - for (b[keep..lb]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; - if (lb > 0 and random.boolean()) b[random.uintLessThan(usize, lb)] ^= 1; - const old = a[0..la]; - const new = b[0..lb]; - const n = @min(old.len, new.len); - const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; - var tail: usize = 0; - while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; - try std.testing.expectEqual(Span{ .head = head, .tail = tail }, spanOf(old, new)); - } -} - fn positionIn(gpa: std.mem.Allocator, f: *State, at: usize) struct { row: usize, col: usize } { const index = lineIndex(gpa, f) catch { const c = modal.positionAt(f.content, at); @@ -1475,27 +1231,6 @@ pub fn looksLikeDiff(head: []const u8) bool { return diff.looksLikeDiff(lines[0..n]); } -test "a +Pager pane holding a diff is drawn and looked at as one; holding other text, as text" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile(""); - const f = &pane.file.?; - p.gpa.free(f.path); - f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); - f.pager = true; - setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); - try std.testing.expect(pane.colorAlgo() == .diff); - try std.testing.expect(pardes.look.diffLines(p, pane) != null); - setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\n a plain log\n")); - try std.testing.expect(pane.colorAlgo() != .diff); -} - -test "a pager's text is a diff when it holds a diff header or a unified hunk" { - try std.testing.expect(looksLikeDiff("commit abc\nAuthor: x\n\n msg\n\ndiff --git a/f b/f\n")); - try std.testing.expect(looksLikeDiff("--- a/f\n+++ b/f\n@@ -1 +1 @@\n-a\n+b\n")); - try std.testing.expect(!looksLikeDiff("commit abc\nAuthor: x\n\n plain log\n")); -} - pub fn restoreSnap(pane: *Pane, f: *State, snap: Text.Place) void { const n = nlines(pane.gpa, f); const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); @@ -1830,52 +1565,6 @@ fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { Stream.paintAhead(p, pane.serial, f.revision, f.path, f.content, start, end); } -test "a long line is painted only around the caret" { - if (!syntax.enabled) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const line = try std.testing.allocator.alloc(u8, 600 << 10); - defer std.testing.allocator.free(line); - for (line, 0..) |*c, i| c.* = if (i % 2 == 0) '1' else ','; - const pane = try p.setTestFile(line); - p.gpa.free(pane.file.?.path); - pane.file.?.path = try p.gpa.dupe(u8, "/tmp/long.json"); - pane.body.cur_col = 300 << 10; - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - _ = try p.render(arena.allocator()); - const f = &pane.file.?; - try std.testing.expect(f.highlights.len == long_paint); - try std.testing.expect(f.highlight_start <= 300 << 10 and f.highlight_start + f.highlights.len >= 300 << 10); -} - -test "a caret deep in a long line scrolls the view sideways to it, measured from the view's edge" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.settings.wrap = false; - const line = try std.testing.allocator.alloc(u8, 500 << 10); - defer std.testing.allocator.free(line); - @memset(line, 'a'); - const pane = try p.setTestFile(line); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - _ = try p.render(arena.allocator()); - // Right, far: the caret ends a margin in from the right edge. - pane.body.cur_col = 400_000; - pane.ensureCursorVisible(); - const w: i32 = @as(i32, pane.cols) - @as(i32, gutterWidth(pane)); - const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2)); - try std.testing.expectEqual(@as(i32, 400_000 - (w - 1 - hmargin)), pane.hscroll); - // Back left of the view: a margin in from the left edge. - pane.body.cur_col = 100_000; - pane.ensureCursorVisible(); - try std.testing.expectEqual(@as(i32, 100_000 - hmargin), pane.hscroll); - // At the start: none. - pane.body.cur_col = 1; - pane.ensureCursorVisible(); - try std.testing.expectEqual(@as(i32, 0), pane.hscroll); -} - pub fn supportsContext(pane: *const Pane) bool { const file = pane.file orelse return false; return file.output == null and file.mini == null and syntax.supportsPath(file.path); @@ -1973,14 +1662,13 @@ fn mapRows(pane: *Pane, f: *State) usize { fn geometryKey(pane: *const Pane, f: *const State) u64 { const t = &f.tables; const facts = .{ - f.revision, f.content.len, f.scroll, pane.hscroll, - pane.rows, pane.cols, pane.tag_rows, pane.collapsed, - pane.query != null, f.pager, f.mini != null, f.output != null, - if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context_revision orelse 0, - f.context_declarations.len, - f.line_starts.len, t.revision orelse 0, t.list.items.len, if (t.pending) |r| r.at else std.math.maxInt(usize), - pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, - pane.view.rect_h, + f.revision, f.content.len, f.scroll, pane.hscroll, + pane.rows, pane.cols, pane.tag_rows, pane.collapsed, + pane.query != null, f.pager, f.mini != null, f.output != null, + if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context_revision orelse 0, + f.context_declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, + if (t.pending) |r| r.at else std.math.maxInt(usize), pane.view.wrap, pane.view.layered, pane.view.body_h, + pane.view.tagline_h, pane.view.rect_h, }; // One hash of them laid out as words: every reader of the map asks for // this key, a hundred times a frame. @@ -2557,6 +2245,317 @@ pub fn paintWordSelection( } } +test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" { + try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81")); + try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe")); + try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80")); + // The whole path the 9P fuzzer took: a body holding it, fitted to a width. + const text = "\xeee\xcc\x81"; + try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); +} + +test "indexed source rows match uncached scans across content changes" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const file = &pane.file.?; + for ([_][]const u8{ "", "one", "one\n", "a\r\nλ界\nlast", "\n\n", "\tλ e\u{301}\n\r\n" }) |content| { + setContent(p, file, try p.gpa.dupe(u8, content)); + // An edit carries a built index forward; it must equal a fresh one. + if (file.line_starts.len > 0) { + const carried = file.line_starts; + const room = indexRoom(file); + defer p.gpa.free(room); + file.line_starts = &.{}; + try std.testing.expectEqualSlices(usize, try lineIndex(p.gpa, file), carried); + p.gpa.free(file.line_starts); + file.line_starts = &.{}; + } + const rows = lineCount(content) + 2; + for ([_]bool{ false, true }) |indexed| { + if (indexed) _ = try lineIndex(p.gpa, file); + try std.testing.expectEqualStrings("", sourceLine(pane, -1)); + for (0..rows) |row| try std.testing.expectEqualStrings( + modal.lineSlice(content, row), + sourceLine(pane, @intCast(row)), + ); + if (!indexed) try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + } + } +} + +test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { + const ref = struct { + fn width(grapheme: []const u8) usize { + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; + return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + } + }.width; + + var one: [1]u8 = undefined; + var b: u8 = 0; + while (b < 0x80) : (b += 1) { + one[0] = b; + try std.testing.expectEqual(ref(one[0..1]), graphemeDisplayWidth(one[0..1])); + } + for ([_][]const u8{ + "e\u{301}", "a\u{903}", "1\u{fe0f}\u{20e3}", "\u{4e16}", + "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", + }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); + // Two invalid bytes are two cells, as surface.zig draws them, where + // vaxis's own count gives the pair one. + try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8")); +} + +test "the ASCII run in fitEnd survives an exhaustive byte sweep" { + const reference = struct { + fn fitEnd(text: []const u8, start: usize, width: usize) usize { + var end = start; + var used: usize = 0; + while (end < text.len) { + const next_end = modal.nextGrapheme(text, end); + const next_used = used +| graphemeDisplayWidth(text[end..next_end]); + if (next_used > width) return if (end == start) next_end else end; + used = next_used; + end = next_end; + } + return end; + } + }.fitEnd; + + const neighbours = [_][]const u8{ + "", "z", "\u{301}", "\u{200d}\u{1f680}", + "\u{903}", "\u{fe0f}", "\u{4e16}", "\u{1f642}", + "\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", + }; + var buf: [16]u8 = undefined; + // The same pair again behind an ASCII prefix, so a break can land exactly at the run boundary + // as well as before it and inside the multi-byte cluster that follows it. + var prefixed: [18]u8 = undefined; + prefixed[0] = 'a'; + prefixed[1] = 'b'; + var b: u8 = 0; + while (b < 0x80) : (b += 1) { + buf[0] = b; + for (neighbours) |tail| { + @memcpy(buf[1..][0..tail.len], tail); + const pair = buf[0 .. 1 + tail.len]; + @memcpy(prefixed[2..][0..pair.len], pair); + for ([_][]const u8{ pair, prefixed[0 .. 2 + pair.len] }) |text| { + var width: usize = 0; + while (width <= text.len + 3) : (width += 1) { + var start: usize = 0; + while (start <= text.len) : (start += 1) { + std.testing.expectEqual( + reference(text, start, width), + fitEnd(text, start, width), + ) catch |e| { + std.debug.print("fitEnd({any}, {d}, {d})\n", .{ text, start, width }); + return e; + }; + } + } + } + } + } +} + +test "the ASCII run in fitEnd cuts where the grapheme walk would" { + const reference = struct { + fn fitEnd(text: []const u8, start: usize, width: usize) usize { + var end = start; + var used: usize = 0; + while (end < text.len) { + const next_end = modal.nextGrapheme(text, end); + const next_used = used +| graphemeDisplayWidth(text[end..next_end]); + if (next_used > width) return if (end == start) next_end else end; + used = next_used; + end = next_end; + } + return end; + } + }.fitEnd; + + const cases = [_][]const u8{ + "", + "hello world", + // the fast path must hand over at the first non-ASCII byte, mid-run + "abc\u{00e9}def", + // a wide glyph is two columns, so a width boundary can land inside it + "ab\u{4e16}\u{754c}cd", + // a cluster the fast path must not split + "a\u{0301}bc", + // tabs and controls are excluded from the fast path by the range test + "ab\tcd", + "ab\rcd", + // an ASCII byte followed by a continuation byte is NOT its own cluster + "e\u{0301}x", + "\u{1f1e6}\u{1f1e7}ok", + }; + for (cases) |text| { + var width: usize = 0; + while (width <= text.len + 3) : (width += 1) { + var start: usize = 0; + while (start <= text.len) : (start += 1) { + try std.testing.expectEqual( + reference(text, start, width), + fitEnd(text, start, width), + ); + } + } + } +} + +test "a line index shifted in place equals a rebuilt one, and the edit turned round gives the one before back" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(11); + const r = prng.random(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..300) |_| try text.append(gpa, "ab\n"[r.uintLessThan(usize, 3)]); + var f: State = .{ .path = &.{}, .content = text.items, .history = undefined }; + _ = try lineIndex(gpa, &f); + defer gpa.free(indexRoom(&f)); + for (0..2000) |round| { + const at = r.uintAtMost(usize, text.items.len); + const del = r.uintAtMost(usize, @min(12, text.items.len - at)); + var ins: [12]u8 = undefined; + const ins_len = r.uintAtMost(usize, 12); + for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + const before = try gpa.dupe(usize, f.line_starts); + defer gpa.free(before); + const cut = try gpa.dupe(u8, text.items[at..][0..del]); + defer gpa.free(cut); + f.content = text.items; + shiftIndex(gpa, &f, at, del, ins[0..ins_len]); + try text.replaceRange(gpa, at, del, ins[0..ins_len]); + var fresh: State = .{ .path = &.{}, .content = text.items, .history = undefined }; + const want = try lineIndex(gpa, &fresh); + defer gpa.free(want); + try std.testing.expectEqualSlices(usize, want, f.line_starts); + // Every tenth turned round in a copy, as a rollback takes it back. + if (round % 10 == 0) { + const room = try gpa.alloc(usize, indexRoom(&f).len); + defer gpa.free(room); + @memcpy(room[0..f.line_starts.len], f.line_starts); + shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); + try std.testing.expectEqualSlices(usize, before, room[0..before.len]); + } + } +} + +test "indexed text rows preserve fragment and allocation failure semantics" { + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("first\n\tλ界\n\nlast\n"); + const text = pane.file.?.content; + allocator.fail_index = allocator.alloc_index; + for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(&pane.body, text, row)); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.line_starts.len); + allocator.fail_index = std.math.maxInt(usize); + _ = try lineIndex(p.gpa, &pane.file.?); + allocator.fail_index = allocator.alloc_index; + const allocations = allocator.allocations; + for ([_][]const u8{ text, text[2..], text[0..8], "other\nrows\n\n", "" }) |fragment| { + for (0..lineCount(fragment) + 2) |row| try std.testing.expectEqualStrings( + modal.lineSlice(fragment, row), + textLine(&pane.body, fragment, row), + ); + } + try std.testing.expectEqual(allocations, allocator.allocations); +} + +test "spanOf by blocks finds the byte loop's ends" { + var prng: std.Random.DefaultPrng = .init(5); + const random = prng.random(); + var a: [160]u8 = undefined; + var b: [160]u8 = undefined; + for (0..4000) |_| { + const la = random.uintLessThan(usize, a.len); + const lb = random.uintLessThan(usize, b.len); + for (a[0..la]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + const keep = @min(la, lb); + @memcpy(b[0..keep], a[0..keep]); + for (b[keep..lb]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + if (lb > 0 and random.boolean()) b[random.uintLessThan(usize, lb)] ^= 1; + const old = a[0..la]; + const new = b[0..lb]; + const n = @min(old.len, new.len); + const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var tail: usize = 0; + while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + try std.testing.expectEqual(Span{ .head = head, .tail = tail }, spanOf(old, new)); + } +} + +test "a +Pager pane holding a diff is drawn and looked at as one; holding other text, as text" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const f = &pane.file.?; + p.gpa.free(f.path); + f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); + f.pager = true; + setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); + try std.testing.expect(pane.colorAlgo() == .diff); + try std.testing.expect(pardes.look.diffLines(p, pane) != null); + setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\n a plain log\n")); + try std.testing.expect(pane.colorAlgo() != .diff); +} + +test "a pager's text is a diff when it holds a diff header or a unified hunk" { + try std.testing.expect(looksLikeDiff("commit abc\nAuthor: x\n\n msg\n\ndiff --git a/f b/f\n")); + try std.testing.expect(looksLikeDiff("--- a/f\n+++ b/f\n@@ -1 +1 @@\n-a\n+b\n")); + try std.testing.expect(!looksLikeDiff("commit abc\nAuthor: x\n\n plain log\n")); +} + +test "a long line is painted only around the caret" { + if (!syntax.enabled) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const line = try std.testing.allocator.alloc(u8, 600 << 10); + defer std.testing.allocator.free(line); + for (line, 0..) |*c, i| c.* = if (i % 2 == 0) '1' else ','; + const pane = try p.setTestFile(line); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/long.json"); + pane.body.cur_col = 300 << 10; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + const f = &pane.file.?; + try std.testing.expect(f.highlights.len == long_paint); + try std.testing.expect(f.highlight_start <= 300 << 10 and f.highlight_start + f.highlights.len >= 300 << 10); +} + +test "a caret deep in a long line scrolls the view sideways to it, measured from the view's edge" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + p.settings.wrap = false; + const line = try std.testing.allocator.alloc(u8, 500 << 10); + defer std.testing.allocator.free(line); + @memset(line, 'a'); + const pane = try p.setTestFile(line); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + // Right, far: the caret ends a margin in from the right edge. + pane.body.cur_col = 400_000; + pane.ensureCursorVisible(); + const w: i32 = @as(i32, pane.cols) - @as(i32, gutterWidth(pane)); + const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2)); + try std.testing.expectEqual(@as(i32, 400_000 - (w - 1 - hmargin)), pane.hscroll); + // Back left of the view: a margin in from the left edge. + pane.body.cur_col = 100_000; + pane.ensureCursorVisible(); + try std.testing.expectEqual(@as(i32, 100_000 - hmargin), pane.hscroll); + // At the start: none. + pane.body.cur_col = 1; + pane.ensureCursorVisible(); + try std.testing.expectEqual(@as(i32, 0), pane.hscroll); +} + test "undo and redo walk back and forth through every step of random edits, joined entries and all" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/src/Handover.zig b/src/Handover.zig index 1b4fed7d..cf672ba4 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -415,7 +415,7 @@ fn carry(io: std.Io, job: *Job) void { const entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ run, pid }) catch unreachable; // under sun_path, checked above var waited: u32 = 0; while (waited < 15_000) : (waited += 50) { - if (libc.kill(pid, @enumFromInt(0)) != 0) + if (libc.kill(pid, @fromBackingInt(@intCast(0))) != 0) return job.post(job.post_ctx, job.seq, false, "the new window ended before it was up"); if (ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256)) |status| { job.gpa.free(status); @@ -506,6 +506,8 @@ fn spawnWindow(job: *Job) !libc.pid_t { // ---- tests ---- +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + /// Two text panes in one column, the lower one `/test.txt`'s twin made by /// New, and the grip of pane `id` let go past the window's edge. fn twoPanes(gpa: std.mem.Allocator) !*Pardes { @@ -658,8 +660,6 @@ test "a column let go over another window goes beside the column the pointer is try std.testing.expect(from.view().ncol == 1 or from.view().cols[c].n == 0 or layout.findPane(from, 0) == null); } -extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; - test "a handover under a runtime directory too long for a window's socket is refused in words, no window made" { if (comptime builtin.os.tag != .linux) return error.SkipZigTest; const gpa = std.testing.allocator; diff --git a/src/Layer.zig b/src/Layer.zig index aa346413..78dfa069 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -179,6 +179,58 @@ pub fn tagAgain(hit: TagHit) ?TagHit { return tagHitIn(hit.kind, hit.id, hit.serial, hit.place, hit.pixel_x, hit.pixel_y, pixelsOf(hit.metrics)); } +// Pointer hits on tag bands: comparing two, and bringing one that left +// its band back onto it. + +/// Whether two pointer hits name the same cell of the same tag line. +pub fn sameCell(a: ?TagHit, b: ?TagHit) bool { + const first = a orelse return b == null; + const second = b orelse return false; + return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.line == second.line and first.col == second.col; +} + +/// The tag column a host's pointer is at. Clamped, a point off the tag is +/// brought back onto line `line` of it, for a drag that leaves it. +pub fn columnAt(p: *const pardes.Pardes, kind: Kind, id: usize, supplied: ?TagHit, clamp: bool, line: u16) ?u16 { + var point = supplied orelse return null; + if (point.kind != kind or point.id != id) return null; + if (clamp and line < point.place.rows) { + const v = point.place.viewport; + const bw: f32 = @floatFromInt(point.metrics.body_w); + const bh: f32 = @floatFromInt(point.metrics.body_h); + const left = @as(f32, @floatFromInt(v.x)) * bw; + const right = @as(f32, @floatFromInt(v.x + v.w)) * bw; + point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); + point.pixel_y = (@as(f32, @floatFromInt(v.y + line)) + 0.5) * bh; + } + return if (layout.reprojectTagHit(p, point)) |mapped| mapped.col else null; +} + +/// A tag caret `w` wide at glyph `x`, its left and right edges in the unit +/// `cell` (a grid cell's width) is in, glyphs `pitch` apart: past a full +/// row's end it sits at the tag's right edge, where the grid's is clamped. +pub fn caretSpan(layer: *const Layer, x: u16, cell: f32, pitch: f32, w: f32) [2]f32 { + const left = @as(f32, @floatFromInt(layer.viewport.x)) * cell; + const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * cell; + const x0 = @min(left + @as(f32, @floatFromInt(x)) * pitch, right - w); + return .{ x0, @min(right, x0 + w) }; +} + +pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { + const spare = cell_h -| tagline_h; + const rows: u32 = @max(1, @as(u32, @intFromFloat(@floor(canvas_h / @as(f32, @floatFromInt(cell_h)))))); + // Every band centers in its cell, so text and anchors sit at the same + // height in the workspace, column and pane tags alike. Only the last row + // faces the window edge. + if (@as(u32, row) + 1 >= rows) return spare; + return spare / 2; +} + +pub fn topbarPaneBorderPixels(cell_h: u32, tagline_h: u32) u32 { + const spare = cell_h -| tagline_h; + return @min(@as(u32, config.gui_topbar_pane_border_px), spare * 2); +} + test "compact body layer rows fill reclaimed height and invert exact boundaries" { const layer: Layer = .{ .serial = 7, .viewport = .{ .x = 4, .y = 3, .w = 40, .h = 10 }, .cols = 40, .rows = 15, .context_rows = 5 }; try std.testing.expectEqual(@as(f32, 120), layer.rowTop(5, 20, 12)); @@ -234,58 +286,6 @@ test "a taller tag's rows are grid rows, each hit on its own line" { try std.testing.expect(layer.bodyHit(120, 100, 10, 20, 6, 12) == null); } -// Pointer hits on tag bands: comparing two, and bringing one that left -// its band back onto it. - -/// Whether two pointer hits name the same cell of the same tag line. -pub fn sameCell(a: ?TagHit, b: ?TagHit) bool { - const first = a orelse return b == null; - const second = b orelse return false; - return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.line == second.line and first.col == second.col; -} - -/// The tag column a host's pointer is at. Clamped, a point off the tag is -/// brought back onto line `line` of it, for a drag that leaves it. -pub fn columnAt(p: *const pardes.Pardes, kind: Kind, id: usize, supplied: ?TagHit, clamp: bool, line: u16) ?u16 { - var point = supplied orelse return null; - if (point.kind != kind or point.id != id) return null; - if (clamp and line < point.place.rows) { - const v = point.place.viewport; - const bw: f32 = @floatFromInt(point.metrics.body_w); - const bh: f32 = @floatFromInt(point.metrics.body_h); - const left = @as(f32, @floatFromInt(v.x)) * bw; - const right = @as(f32, @floatFromInt(v.x + v.w)) * bw; - point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); - point.pixel_y = (@as(f32, @floatFromInt(v.y + line)) + 0.5) * bh; - } - return if (layout.reprojectTagHit(p, point)) |mapped| mapped.col else null; -} - -/// A tag caret `w` wide at glyph `x`, its left and right edges in the unit -/// `cell` (a grid cell's width) is in, glyphs `pitch` apart: past a full -/// row's end it sits at the tag's right edge, where the grid's is clamped. -pub fn caretSpan(layer: *const Layer, x: u16, cell: f32, pitch: f32, w: f32) [2]f32 { - const left = @as(f32, @floatFromInt(layer.viewport.x)) * cell; - const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * cell; - const x0 = @min(left + @as(f32, @floatFromInt(x)) * pitch, right - w); - return .{ x0, @min(right, x0 + w) }; -} - -pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - const spare = cell_h -| tagline_h; - const rows: u32 = @max(1, @as(u32, @intFromFloat(@floor(canvas_h / @as(f32, @floatFromInt(cell_h)))))); - // Every band centers in its cell, so text and anchors sit at the same - // height in the workspace, column and pane tags alike. Only the last row - // faces the window edge. - if (@as(u32, row) + 1 >= rows) return spare; - return spare / 2; -} - -pub fn topbarPaneBorderPixels(cell_h: u32, tagline_h: u32) u32 { - const spare = cell_h -| tagline_h; - return @min(@as(u32, config.gui_topbar_pane_border_px), spare * 2); -} - test "tagline bands center in their cells and the last row faces the window edge" { const cell_h: u32 = 20; const tagline_h: u32 = 16; diff --git a/src/Messages.zig b/src/Messages.zig index e4328a1e..6913f99f 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -440,18 +440,6 @@ pub fn zonWhy(diag: *const std.zon.parse.Diagnostics, buf: []u8) []const u8 { return w.buffered(); } -test "errors are said in words, and a ZON failure names its line" { - var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings("file not found", errorWords(error.FileNotFound, &buf)); - try std.testing.expectEqualStrings("too large", errorWords(error.FileTooLarge, &buf)); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var diag: std.zon.parse.Diagnostics = undefined; - const T = struct { a: u8 }; - try std.testing.expectError(error.ParseZon, std.zon.parse.fromSlice(T, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = ".{\n .a = 1,\n .b = 2 }", .diagnostics = &diag })); - try std.testing.expect(std.mem.startsWith(u8, zonWhy(&diag, &buf), "line 3: ")); -} - /// The longest start of `text` that fits `max` bytes and ends between /// words (or, with no space to cut at, between characters). pub fn clip(text: []const u8, max: usize) []const u8 { @@ -490,12 +478,6 @@ pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { setMessage(p, id, text); } -test "an error reads as words and a failure is cut between them" { - try std.testing.expectEqualStrings("go", clip("go haskell", 4)); - try std.testing.expectEqualStrings("go haskell", clip("go haskell", 10)); - try std.testing.expectEqualStrings("\u{e9}", clip("\u{e9}\u{e9}", 3)); -} - /// The one place that decides which transient lines a pane is showing and /// in what order. Everything downstream reads the answer: the body layer /// so it does not paint under them, and the paint pass so it can stack @@ -557,6 +539,24 @@ fn collectBands(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { n.len -= @intCast(drop); } +test "errors are said in words, and a ZON failure names its line" { + var buf: [128]u8 = undefined; + try std.testing.expectEqualStrings("file not found", errorWords(error.FileNotFound, &buf)); + try std.testing.expectEqualStrings("too large", errorWords(error.FileTooLarge, &buf)); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var diag: std.zon.parse.Diagnostics = undefined; + const T = struct { a: u8 }; + try std.testing.expectError(error.ParseZon, std.zon.parse.fromSlice(T, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = ".{\n .a = 1,\n .b = 2 }", .diagnostics = &diag })); + try std.testing.expect(std.mem.startsWith(u8, zonWhy(&diag, &buf), "line 3: ")); +} + +test "an error reads as words and a failure is cut between them" { + try std.testing.expectEqualStrings("go", clip("go haskell", 4)); + try std.testing.expectEqualStrings("go haskell", clip("go haskell", 10)); + try std.testing.expectEqualStrings("\u{e9}", clip("\u{e9}\u{e9}", 3)); +} + test "the message log keeps what the row forgets, and collapses repeats" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); diff --git a/src/Output.zig b/src/Output.zig index f1ce7ab9..0161878e 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -144,103 +144,6 @@ pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) R return row; } -test "callstack guides and Look locations share result decoration" { - const from: State = .{ .from = .{ .query = .callstack } }; - const loc = decorateRow(from, "╰──┬ lib.rs:2:8-10 fn add() {", null); - try std.testing.expectEqual(@as(usize, "╰──┬ lib.rs:2:8-10".len), loc.location_end); - try std.testing.expect(!loc.declaration); - try std.testing.expect(!usesLocationsConfig(from.from)); - try std.testing.expect(!traits(from.from).jumps); - const call_line = " lib.rs:12:12-20 return calculate(value);"; - const call = decorateRow(from, call_line, null); - try std.testing.expectEqualStrings("calculate", call_line[call.mark_start..call.mark_end]); - const reference = decorateRow(.{ .from = .{ .query = .references } }, call_line[4..], null); - try std.testing.expectEqual(reference.mark_start + 4, call.mark_start); - try std.testing.expectEqual(reference.mark_end + 4, call.mark_end); - try std.testing.expectEqual(reference.location_end + 4, call.location_end); - const tab_line = " tab.zig:4:9-11 \treturn run();"; - const tab_call = decorateRow(from, tab_line, null); - try std.testing.expectEqualStrings("run", tab_line[tab_call.mark_start..tab_call.mark_end]); -} - -test "result decoration follows source byte ranges and diagnostic provenance" { - const row = decorateRow(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;", null); - try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]); - const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null); - try std.testing.expectEqual(@as(usize, 0), prose.mark_end); - const diagnostic = decorateRow(.{ .from = .{ .query = .diagnostics } }, "src/a.rs:3:5-7 warning: unused", null); - try std.testing.expectEqual(.warning, diagnostic.severity); - try std.testing.expectEqualStrings("warning:", "src/a.rs:3:5-7 warning: unused"[diagnostic.mark_start..diagnostic.mark_end]); - const malformed = decorateRow(.{ .from = .search }, "src/a.rs:3:99999999999999999999-99999999999999999999 text", null); - try std.testing.expect(malformed.mark_end <= "src/a.rs:3:99999999999999999999-99999999999999999999 text".len); - const snippet = "src/a.rs:3:14-16 \t\tfoo + 界 + foo"; - for ([_]lsp.Kind{ .definition, .declaration, .type_definition, .implementation, .references }) |kind| { - const occurrence = decorateRow(.{ .from = .{ .query = kind } }, snippet, null); - try std.testing.expectEqualStrings("foo", snippet[occurrence.mark_start..occurrence.mark_end]); - } - for ([_]lsp.Kind{ .document_symbols, .workspace_symbols, .completion, .incoming_calls, .outgoing_calls, .supertypes, .subtypes, .rename }) |kind| { - const label = decorateRow(.{ .from = .{ .query = kind } }, snippet, null); - try std.testing.expectEqual(@as(usize, 0), label.mark_end); - } -} - -test "stacked empty previews distinguish separators from trailing newlines" { - var path = [_]u8{ 'x', '.', 'c' }; - const rows = [_]locations.Row{ - .{ .kind = .match, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 7, .code_start = 7 }, - .{ .kind = .preview, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 0, .code_start = 0 }, - }; - try std.testing.expect(locations.sameInput("x.c:1:1 ", "x.c:1:1\n", &rows, .stacked)); - try std.testing.expect(locations.sameInput("x.c:1:1 \n", "x.c:1:1\n\n", &rows, .stacked)); - try std.testing.expect(!locations.sameInput("x.c:1:1 ", "x.c:1:1\n\n", &rows, .stacked)); - try std.testing.expect(!locations.sameInput("x.c:1:1 \n", "x.c:1:1\n", &rows, .stacked)); -} - -test "two words looked for in a terminal share the directory's one +Search" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const term = for (p.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break id; - } else return error.SkipZigTest; - p.word_look = true; - defer p.word_look = false; - try fillResults(p, term, "/work", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\n"), null); - try fillResults(p, term, "/work", .search, "bar", try p.gpa.dupe(u8, "a.txt:2:1 bar\n"), null); - var searches: usize = 0; - for (p.panes) |slot| { - const f = (slot orelse continue).file orelse continue; - searches += @intFromBool(std.mem.eql(u8, f.path, "/work/+Search")); - } - try std.testing.expectEqual(@as(usize, 1), searches); -} - -test "Lspinfo and Lspwhy fill one +Lsp in a directory" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - _ = try p.setTestFile("x\n"); - try fillResults(p, 0, "/work", .{ .query = .status }, "", try p.gpa.dupe(u8, "servers\n"), null); - try fillResults(p, 0, "/work", .{ .query = .explain }, "", try p.gpa.dupe(u8, "why\n"), null); - var lsp_panes: usize = 0; - for (p.panes) |slot| { - const f = (slot orelse continue).file orelse continue; - if (std.mem.eql(u8, f.path, "/work/+Lsp")) { - lsp_panes += 1; - try std.testing.expectEqualStrings("why\n", f.content); - } - } - try std.testing.expectEqual(@as(usize, 1), lsp_panes); -} - -test "plain output does not opt into location decoration" { - const report = decorateRow(.{ .from = .{ .cmd = .LocationsConfig } }, "LocationsConfig context:5 tscontext:on", null); - try std.testing.expectEqualDeep(RowDecoration{}, report); - const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null); - try std.testing.expectEqualDeep(RowDecoration{}, prose); - const errors = decorateRow(.{ .from = .errors }, "src/a.rs:3:5-7 error: prose", null); - try std.testing.expectEqualDeep(RowDecoration{}, errors); - try std.testing.expect(traits(.{ .query = .completion }).locations); -} - pub fn setArg(o: *State, text: []const u8) error{ArgumentTooLong}!void { if (text.len > max_arg) return error.ArgumentTooLong; o.arg_len = @intCast(text.len); @@ -950,37 +853,6 @@ pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { return openRead(p, id, .{ .cmd = .Help }, prefix, content); } -test "full Help renders builtin rows, a call hierarchy guide, then language keys" { - const core = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const content = try helpContent(core, std.testing.allocator, ""); - defer std.testing.allocator.free(content); - - // FIRST blank line: the end of the header (the footer opens with one too) - const body = content[(std.mem.indexOf(u8, content, "\n\n") orelse - return error.MissingHelpHeader) + 2 ..]; - var lines = std.mem.splitScalar(u8, body, '\n'); - for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd)) - try std.testing.expectEqualStrings(row.line, lines.next() orelse - return error.MissingBuiltinHelpRow); - // The short call guide disambiguates the three related commands. - try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp); - // The language keys close the page. - try std.testing.expectEqualStrings("", lines.next() orelse - return error.MissingLanguageKeys); - try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse - return error.MissingLanguageKeys); - try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); - // The language group also explains call commands, without the motion footer. - const group = try helpContent(core, std.testing.allocator, "l"); - defer std.testing.allocator.free(group); - try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); - try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); -} - /// Where a dump goes by default, as the session's environment says (the /// authority's, `tape.authority`): in `buf`. fn dumpDirectory(buf: []u8) []const u8 { @@ -1118,3 +990,131 @@ fn openRead(p: *Pardes, id: usize, from: Origin, arg: []const u8, content: []u8) exec.placeNew(p, id, id, free, if (from == .errors) .errors else .doc); p.view().active = free; } + +test "callstack guides and Look locations share result decoration" { + const from: State = .{ .from = .{ .query = .callstack } }; + const loc = decorateRow(from, "╰──┬ lib.rs:2:8-10 fn add() {", null); + try std.testing.expectEqual(@as(usize, "╰──┬ lib.rs:2:8-10".len), loc.location_end); + try std.testing.expect(!loc.declaration); + try std.testing.expect(!usesLocationsConfig(from.from)); + try std.testing.expect(!traits(from.from).jumps); + const call_line = " lib.rs:12:12-20 return calculate(value);"; + const call = decorateRow(from, call_line, null); + try std.testing.expectEqualStrings("calculate", call_line[call.mark_start..call.mark_end]); + const reference = decorateRow(.{ .from = .{ .query = .references } }, call_line[4..], null); + try std.testing.expectEqual(reference.mark_start + 4, call.mark_start); + try std.testing.expectEqual(reference.mark_end + 4, call.mark_end); + try std.testing.expectEqual(reference.location_end + 4, call.location_end); + const tab_line = " tab.zig:4:9-11 \treturn run();"; + const tab_call = decorateRow(from, tab_line, null); + try std.testing.expectEqualStrings("run", tab_line[tab_call.mark_start..tab_call.mark_end]); +} + +test "result decoration follows source byte ranges and diagnostic provenance" { + const row = decorateRow(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;", null); + try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]); + const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null); + try std.testing.expectEqual(@as(usize, 0), prose.mark_end); + const diagnostic = decorateRow(.{ .from = .{ .query = .diagnostics } }, "src/a.rs:3:5-7 warning: unused", null); + try std.testing.expectEqual(.warning, diagnostic.severity); + try std.testing.expectEqualStrings("warning:", "src/a.rs:3:5-7 warning: unused"[diagnostic.mark_start..diagnostic.mark_end]); + const malformed = decorateRow(.{ .from = .search }, "src/a.rs:3:99999999999999999999-99999999999999999999 text", null); + try std.testing.expect(malformed.mark_end <= "src/a.rs:3:99999999999999999999-99999999999999999999 text".len); + const snippet = "src/a.rs:3:14-16 \t\tfoo + 界 + foo"; + for ([_]lsp.Kind{ .definition, .declaration, .type_definition, .implementation, .references }) |kind| { + const occurrence = decorateRow(.{ .from = .{ .query = kind } }, snippet, null); + try std.testing.expectEqualStrings("foo", snippet[occurrence.mark_start..occurrence.mark_end]); + } + for ([_]lsp.Kind{ .document_symbols, .workspace_symbols, .completion, .incoming_calls, .outgoing_calls, .supertypes, .subtypes, .rename }) |kind| { + const label = decorateRow(.{ .from = .{ .query = kind } }, snippet, null); + try std.testing.expectEqual(@as(usize, 0), label.mark_end); + } +} + +test "stacked empty previews distinguish separators from trailing newlines" { + var path = [_]u8{ 'x', '.', 'c' }; + const rows = [_]locations.Row{ + .{ .kind = .match, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 7, .code_start = 7 }, + .{ .kind = .preview, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 0, .code_start = 0 }, + }; + try std.testing.expect(locations.sameInput("x.c:1:1 ", "x.c:1:1\n", &rows, .stacked)); + try std.testing.expect(locations.sameInput("x.c:1:1 \n", "x.c:1:1\n\n", &rows, .stacked)); + try std.testing.expect(!locations.sameInput("x.c:1:1 ", "x.c:1:1\n\n", &rows, .stacked)); + try std.testing.expect(!locations.sameInput("x.c:1:1 \n", "x.c:1:1\n", &rows, .stacked)); +} + +test "two words looked for in a terminal share the directory's one +Search" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const term = for (p.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break id; + } else return error.SkipZigTest; + p.word_look = true; + defer p.word_look = false; + try fillResults(p, term, "/work", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\n"), null); + try fillResults(p, term, "/work", .search, "bar", try p.gpa.dupe(u8, "a.txt:2:1 bar\n"), null); + var searches: usize = 0; + for (p.panes) |slot| { + const f = (slot orelse continue).file orelse continue; + searches += @intFromBool(std.mem.eql(u8, f.path, "/work/+Search")); + } + try std.testing.expectEqual(@as(usize, 1), searches); +} + +test "Lspinfo and Lspwhy fill one +Lsp in a directory" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + try fillResults(p, 0, "/work", .{ .query = .status }, "", try p.gpa.dupe(u8, "servers\n"), null); + try fillResults(p, 0, "/work", .{ .query = .explain }, "", try p.gpa.dupe(u8, "why\n"), null); + var lsp_panes: usize = 0; + for (p.panes) |slot| { + const f = (slot orelse continue).file orelse continue; + if (std.mem.eql(u8, f.path, "/work/+Lsp")) { + lsp_panes += 1; + try std.testing.expectEqualStrings("why\n", f.content); + } + } + try std.testing.expectEqual(@as(usize, 1), lsp_panes); +} + +test "plain output does not opt into location decoration" { + const report = decorateRow(.{ .from = .{ .cmd = .LocationsConfig } }, "LocationsConfig context:5 tscontext:on", null); + try std.testing.expectEqualDeep(RowDecoration{}, report); + const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null); + try std.testing.expectEqualDeep(RowDecoration{}, prose); + const errors = decorateRow(.{ .from = .errors }, "src/a.rs:3:5-7 error: prose", null); + try std.testing.expectEqualDeep(RowDecoration{}, errors); + try std.testing.expect(traits(.{ .query = .completion }).locations); +} + +test "full Help renders builtin rows, a call hierarchy guide, then language keys" { + const core = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const content = try helpContent(core, std.testing.allocator, ""); + defer std.testing.allocator.free(content); + + // FIRST blank line: the end of the header (the footer opens with one too) + const body = content[(std.mem.indexOf(u8, content, "\n\n") orelse + return error.MissingHelpHeader) + 2 ..]; + var lines = std.mem.splitScalar(u8, body, '\n'); + for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd)) + try std.testing.expectEqualStrings(row.line, lines.next() orelse + return error.MissingBuiltinHelpRow); + // The short call guide disambiguates the three related commands. + try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp); + // The language keys close the page. + try std.testing.expectEqualStrings("", lines.next() orelse + return error.MissingLanguageKeys); + try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse + return error.MissingLanguageKeys); + try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); + // The language group also explains call commands, without the motion footer. + const group = try helpContent(core, std.testing.allocator, "l"); + defer std.testing.allocator.free(group); + try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); + try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); +} diff --git a/src/Pipe.zig b/src/Pipe.zig index 4d525f01..8c25a797 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -36,14 +36,6 @@ pub fn deinit(pipe: *Pipe, gpa: std.mem.Allocator) void { pipe.writes.deinit(gpa); } -fn nextPipeEffect(p: *Pardes) ?u32 { - while (p.nextEffect()) |effect| switch (effect) { - .pipe => |request| return request.id, - else => {}, - }; - return null; -} - /// The tag-tail marker each behaviour arms with. One function so the prompt /// that is DRAWN and the command that is PARSED can never disagree. pub fn pipeMarker(how: modal.Normal.PipeBehavior) []const u8 { @@ -329,6 +321,14 @@ pub fn pipeResponse( t.show(); } +fn nextPipeEffect(p: *Pardes) ?u32 { + while (p.nextEffect()) |effect| switch (effect) { + .pipe => |request| return request.id, + else => {}, + }; + return null; +} + test "selection pipe prompt submits exact request and Escape cancels" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); diff --git a/src/Store.zig b/src/Store.zig index 1545e537..61678be6 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -256,6 +256,8 @@ pub fn closedAddress(word: []const u8) ?u32 { const testing = std.testing; +const panes_mod = @import("panes.zig"); + /// A window keeping its state in `dir` (never the user's DumpDir). fn testWindow(dir: []const u8) !*Pardes { var config: [4200]u8 = undefined; @@ -344,5 +346,3 @@ test "store: a closed pane comes back where it was, its rows from the pane that defer w.deinit(); try testing.expectEqual(@as(usize, 0), w.store.closed.items.len); } - -const panes_mod = @import("panes.zig"); diff --git a/src/builtins.zig b/src/builtins.zig index c41b3e1b..2e8397e6 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -269,217 +269,6 @@ pub const registry = struct { } }; -test "capabilities exactly gate setting builtins" { - const Builtin = registry.Builtin(); - for (config.Runtime.settings) |setting| { - const registered = std.meta.stringToEnum(Builtin, setting.word) != null; - try std.testing.expectEqual(setting.enabled(capabilities), registered); - } -} - -test "a builtin's scope is the pane unless it says session, and every setting is the session's" { - const Builtin = registry.Builtin(); - try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Del)); - try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Save)); - try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Newcol)); - try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Kill)); - try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Verbose)); - for (comptime settingList()) |setting| - try std.testing.expectEqual(Scope.session, registry.scope(std.meta.stringToEnum(Builtin, setting.word).?)); -} - -test "Exit asks once about unsaved text, and quits when asked again" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("saved\n"); - pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified - pane.file.?.saved_hash = 0; // edited: what it had is not what it has - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(!p.quit); - try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); - // Told once, and nothing edited since: the second Exit quits. - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(p.quit); -} - -test "Exit over a ctl write or a click names every pane it asks about, a second only those edited since, and the next discards them all" { - for ([_]bool{ false, true }) |clicked| { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const first = try p.setTestFile("saved\n"); - first.file.?.saved_revision = first.file.?.revision -% 1; - first.file.?.saved_hash = 0; // edited: what it had is not what it has - p.newScratchBelow(p.view().active); - const second = p.panes[p.view().active].?; - panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('x')))); - try std.testing.expect(second.file.?.revision != second.file.?.saved_revision); - // A ctl write, or a click through exec (ctl.captured). - if (clicked) p.fs.capturing = true else p.fs.no_prompt = true; - defer p.fs.capturing = false; - defer p.fs.no_prompt = false; - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(!p.quit); - // Two: counted, never a list cut short; `unsaved` records name them. - try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]); - const log = p.fs.log.buf.items; - var rec: [64]u8 = undefined; - for ([_]*const Pane{ first, second }) |pane| - try std.testing.expect(std.mem.indexOf(u8, log, try std.fmt.bufPrint(&rec, "unsaved {d} ", .{pane.serial})) != null); - // The whole list stays in +Unsaved; the notice is short. - try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) != null); - try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), "\nExit again to discard\n")); - var noticed = false; - for (p.panes) |slot| if (slot) |pane| { - noticed = noticed or std.mem.eql(u8, pane.msg[0..pane.msg_len], "2 unsaved panes \u{2014} Exit again to discard"); - }; - try std.testing.expect(noticed); - // Edited since: only that one is named again (acme's rule). - p.fs.failure_len = 0; - panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y')))); - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(!p.quit); - const again = p.fs.failure[0..p.fs.failure_len]; - try std.testing.expect(std.mem.indexOf(u8, again, first.file.?.path) == null); - // The one +Unsaved, filled again. - var kept: usize = 0; - for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| { - kept += @intFromBool(o.from == .unsaved); - }; - try std.testing.expectEqual(@as(usize, 1), kept); - try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) == null); - try std.testing.expect(std.mem.startsWith(u8, again, second.file.?.path)); - p.fs.failure_len = 0; - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(p.quit); - } -} - -/// What +Unsaved holds: the list a refusal over unsaved panes keeps. -fn unsavedList(p: *Pardes) []const u8 { - for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| if (o.from == .unsaved) return f.content; - return ""; -} - -/// A dump file that exists, for a Restore to get past reading it. -fn testDump(buf: []u8) ![]const u8 { - var tmp = std.testing.tmpDir(.{}); - // A real dump: a Restore reads it through before it asks anything. - const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer source.deinit(); - try pardes.dump.dumpState(source); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = source.dump_out.? }); - var dir: [4096]u8 = undefined; - const at = dir[0..try tmp.dir.realPath(std.testing.io, &dir)]; - return std.fmt.bufPrint(buf, "Restore {s}/d.zon", .{at}); -} - -test "Restore asks about unsaved text as Exit does, and restores when asked again" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("saved\n"); - pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified - pane.file.?.saved_hash = 0; // edited: what it had is not what it has - var line_buf: [4200]u8 = undefined; - const line = try testDump(&line_buf); - try std.testing.expect(p.executeBuiltinLine(p.view().active, line)); - try std.testing.expect(p.restore_req == null); - try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nRestore again to discard\n")); - try std.testing.expect(p.executeBuiltinLine(p.view().active, line)); - try std.testing.expectEqualStrings(line["Restore ".len..], p.restore_req.?); -} - -test "a Restore of a dump that cannot be read says so, before the unsaved-text warning" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("saved\n"); - pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified - pane.file.?.saved_hash = 0; // edited: what it had is not what it has - p.fs.no_prompt = true; - defer p.fs.no_prompt = false; - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Restore /nope/missing.zon")); - try std.testing.expect(p.restore_req == null); - try std.testing.expectEqualStrings("Restore: /nope/missing.zon: no such file", p.fs.failure[0..p.fs.failure_len]); - // No warning spent: the Exit after it still asks. - try std.testing.expect(pane.discard_warned == null); -} - -test "a Restore's warning is not an Exit's: each word is warned on its own" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("saved\n"); - pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified - pane.file.?.saved_hash = 0; // edited: what it had is not what it has - var line_buf: [4200]u8 = undefined; - try std.testing.expect(p.executeBuiltinLine(p.view().active, try testDump(&line_buf))); - try std.testing.expect(p.restore_req == null); - // The Restore warned; an Exit after it has not been, and asks. - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(!p.quit); - try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(p.quit); -} - -test "Kill stops the commands pardes typed, bare all and by name those that match, and never quits" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const term = p.view().active; - try std.testing.expect(p.panes[term].?.isTerminal()); - const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - p.update(.{ .output = .{ .pane = @intCast(term), .bytes = prompt } }); - while (p.nextEffect()) |_| {} - // The host the core asks: how many it was asked to stop, and whether - // their shells run jobs in groups of their own. - const killed = struct { - var asked: usize = 0; - var job_control = true; - const vtable: pardes.Host.VTable = .{ .kill_job = answer }; - fn answer(_: ?*anyopaque, _: u8) bool { - asked += 1; - return job_control; - } - fn count(pp: *Pardes, line: []const u8) usize { - asked = 0; - _ = pp.executeBuiltinLine(pp.view().active, line); - return asked; - } - }; - p.host = .{ .vtable = &killed.vtable }; - // Nothing running: nothing to stop, and never the shell; said. - try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); - try std.testing.expectEqualStrings("Kill: nothing running", p.panes[term].?.msg[0..p.panes[term].?.msg_len]); - _ = exec.execute(p, term, "make -j8"); - while (p.nextEffect()) |_| {} - // Typed but not started yet (no C mark): not running. - try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); - p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;C;aid=pardes\x07" } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill ls")); - try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill ls make")); - try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); - try std.testing.expect(!p.quit); - // With job control off there is no job apart from the shell: said, and - // over ctl the write fails with it. - killed.job_control = false; - p.fs.no_prompt = true; - try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); - try std.testing.expectStringStartsWith(p.fs.failure[0..p.fs.failure_len], "Kill: no job to signal"); - p.fs.no_prompt = false; - p.fs.failure_len = 0; - killed.job_control = true; - // Ended (a D mark): nothing to stop again. - p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;D;143;aid=pardes\x07" ++ prompt } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); -} - -test "Look does not announce itself on the message row; Del still does" { - const Builtin = registry.Builtin(); - try std.testing.expect(!registry.announces(Builtin.Look)); - try std.testing.expect(registry.announces(Builtin.Del)); -} - // ---- the two acme verbs ---- /// Look at its argument: open the file or address it names, else find the word, as a right click does. @@ -2061,6 +1850,217 @@ pub const Lspwhy = struct { } }; +/// What +Unsaved holds: the list a refusal over unsaved panes keeps. +fn unsavedList(p: *Pardes) []const u8 { + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| if (o.from == .unsaved) return f.content; + return ""; +} + +/// A dump file that exists, for a Restore to get past reading it. +fn testDump(buf: []u8) ![]const u8 { + var tmp = std.testing.tmpDir(.{}); + // A real dump: a Restore reads it through before it asks anything. + const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer source.deinit(); + try pardes.dump.dumpState(source); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = source.dump_out.? }); + var dir: [4096]u8 = undefined; + const at = dir[0..try tmp.dir.realPath(std.testing.io, &dir)]; + return std.fmt.bufPrint(buf, "Restore {s}/d.zon", .{at}); +} + +test "capabilities exactly gate setting builtins" { + const Builtin = registry.Builtin(); + for (config.Runtime.settings) |setting| { + const registered = std.meta.stringToEnum(Builtin, setting.word) != null; + try std.testing.expectEqual(setting.enabled(capabilities), registered); + } +} + +test "a builtin's scope is the pane unless it says session, and every setting is the session's" { + const Builtin = registry.Builtin(); + try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Del)); + try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Save)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Newcol)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Kill)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Verbose)); + for (comptime settingList()) |setting| + try std.testing.expectEqual(Scope.session, registry.scope(std.meta.stringToEnum(Builtin, setting.word).?)); +} + +test "Exit asks once about unsaved text, and quits when asked again" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(!p.quit); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); + // Told once, and nothing edited since: the second Exit quits. + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(p.quit); +} + +test "Exit over a ctl write or a click names every pane it asks about, a second only those edited since, and the next discards them all" { + for ([_]bool{ false, true }) |clicked| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const first = try p.setTestFile("saved\n"); + first.file.?.saved_revision = first.file.?.revision -% 1; + first.file.?.saved_hash = 0; // edited: what it had is not what it has + p.newScratchBelow(p.view().active); + const second = p.panes[p.view().active].?; + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('x')))); + try std.testing.expect(second.file.?.revision != second.file.?.saved_revision); + // A ctl write, or a click through exec (ctl.captured). + if (clicked) p.fs.capturing = true else p.fs.no_prompt = true; + defer p.fs.capturing = false; + defer p.fs.no_prompt = false; + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(!p.quit); + // Two: counted, never a list cut short; `unsaved` records name them. + try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]); + const log = p.fs.log.buf.items; + var rec: [64]u8 = undefined; + for ([_]*const Pane{ first, second }) |pane| + try std.testing.expect(std.mem.indexOf(u8, log, try std.fmt.bufPrint(&rec, "unsaved {d} ", .{pane.serial})) != null); + // The whole list stays in +Unsaved; the notice is short. + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) != null); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), "\nExit again to discard\n")); + var noticed = false; + for (p.panes) |slot| if (slot) |pane| { + noticed = noticed or std.mem.eql(u8, pane.msg[0..pane.msg_len], "2 unsaved panes \u{2014} Exit again to discard"); + }; + try std.testing.expect(noticed); + // Edited since: only that one is named again (acme's rule). + p.fs.failure_len = 0; + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y')))); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(!p.quit); + const again = p.fs.failure[0..p.fs.failure_len]; + try std.testing.expect(std.mem.indexOf(u8, again, first.file.?.path) == null); + // The one +Unsaved, filled again. + var kept: usize = 0; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| { + kept += @intFromBool(o.from == .unsaved); + }; + try std.testing.expectEqual(@as(usize, 1), kept); + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) == null); + try std.testing.expect(std.mem.startsWith(u8, again, second.file.?.path)); + p.fs.failure_len = 0; + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(p.quit); + } +} + +test "Restore asks about unsaved text as Exit does, and restores when asked again" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + var line_buf: [4200]u8 = undefined; + const line = try testDump(&line_buf); + try std.testing.expect(p.executeBuiltinLine(p.view().active, line)); + try std.testing.expect(p.restore_req == null); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nRestore again to discard\n")); + try std.testing.expect(p.executeBuiltinLine(p.view().active, line)); + try std.testing.expectEqualStrings(line["Restore ".len..], p.restore_req.?); +} + +test "a Restore of a dump that cannot be read says so, before the unsaved-text warning" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + p.fs.no_prompt = true; + defer p.fs.no_prompt = false; + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Restore /nope/missing.zon")); + try std.testing.expect(p.restore_req == null); + try std.testing.expectEqualStrings("Restore: /nope/missing.zon: no such file", p.fs.failure[0..p.fs.failure_len]); + // No warning spent: the Exit after it still asks. + try std.testing.expect(pane.discard_warned == null); +} + +test "a Restore's warning is not an Exit's: each word is warned on its own" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + var line_buf: [4200]u8 = undefined; + try std.testing.expect(p.executeBuiltinLine(p.view().active, try testDump(&line_buf))); + try std.testing.expect(p.restore_req == null); + // The Restore warned; an Exit after it has not been, and asks. + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(!p.quit); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(p.quit); +} + +test "Kill stops the commands pardes typed, bare all and by name those that match, and never quits" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const term = p.view().active; + try std.testing.expect(p.panes[term].?.isTerminal()); + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = prompt } }); + while (p.nextEffect()) |_| {} + // The host the core asks: how many it was asked to stop, and whether + // their shells run jobs in groups of their own. + const killed = struct { + var asked: usize = 0; + var job_control = true; + const vtable: pardes.Host.VTable = .{ .kill_job = answer }; + fn answer(_: ?*anyopaque, _: u8) bool { + asked += 1; + return job_control; + } + fn count(pp: *Pardes, line: []const u8) usize { + asked = 0; + _ = pp.executeBuiltinLine(pp.view().active, line); + return asked; + } + }; + p.host = .{ .vtable = &killed.vtable }; + // Nothing running: nothing to stop, and never the shell; said. + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); + try std.testing.expectEqualStrings("Kill: nothing running", p.panes[term].?.msg[0..p.panes[term].?.msg_len]); + _ = exec.execute(p, term, "make -j8"); + while (p.nextEffect()) |_| {} + // Typed but not started yet (no C mark): not running. + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;C;aid=pardes\x07" } }); + while (p.nextEffect()) |_| {} + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill ls")); + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill ls make")); + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); + try std.testing.expect(!p.quit); + // With job control off there is no job apart from the shell: said, and + // over ctl the write fails with it. + killed.job_control = false; + p.fs.no_prompt = true; + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); + try std.testing.expectStringStartsWith(p.fs.failure[0..p.fs.failure_len], "Kill: no job to signal"); + p.fs.no_prompt = false; + p.fs.failure_len = 0; + killed.job_control = true; + // Ended (a D mark): nothing to stop again. + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;D;143;aid=pardes\x07" ++ prompt } }); + while (p.nextEffect()) |_| {} + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); +} + +test "Look does not announce itself on the message row; Del still does" { + const Builtin = registry.Builtin(); + try std.testing.expect(!registry.announces(Builtin.Look)); + try std.testing.expect(registry.announces(Builtin.Del)); +} + test "Exit and Restore name a modified +New scratch as well as files" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); diff --git a/src/c_heap.zig b/src/c_heap.zig index efd2064d..51cfc137 100644 --- a/src/c_heap.zig +++ b/src/c_heap.zig @@ -103,6 +103,11 @@ pub fn Heap(comptime current: *const std.mem.Allocator) type { var test_allocator: std.mem.Allocator = undefined; +/// Never written, as a release session's zstd heap's allocator was: a +/// constant to the compiler, `ptr` (undefined in std's stateless +/// allocators) whatever it likes at each comparison. +var stateless: std.mem.Allocator = std.heap.page_allocator; + test "a C heap block keeps its bytes, frees exactly, and goes back where it came from" { const heap = Heap(&test_allocator); test_allocator = std.testing.allocator; @@ -141,11 +146,6 @@ test "a C heap block keeps its bytes, frees exactly, and goes back where it came heap.free(null); } -/// Never written, as a release session's zstd heap's allocator was: a -/// constant to the compiler, `ptr` (undefined in std's stateless -/// allocators) whatever it likes at each comparison. -var stateless: std.mem.Allocator = std.heap.page_allocator; - test "a heap over a stateless allocator that is never repointed names it once" { const heap = Heap(&stateless); const before = allocators_len.load(.monotonic); diff --git a/src/colors.zig b/src/colors.zig index cb5dbe75..bc59c334 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -89,60 +89,6 @@ fn focusTint(th: *const Theme) [3]u8 { return best; } -test "every native theme's separators stand off its page, and its focus tint off its tag" { - for (themes[0..native_count]) |*theme| { - const chrome = ChromeTheme.fromTheme(theme); - const page = theme.bg orelse null_page; - try std.testing.expect(contrast(chrome.border, page) >= separator_floor); - // A dark page's focused tag is told by its band too, not the grip - // alone; acme's (light, and acme's own) is told by its button. - if (relativeLuminance(page) < 0.18) try std.testing.expect(theme.tag_active_bg != null); - if (theme.tag_active_bg) |own| { - try std.testing.expect(contrast(chrome.tag_active_bg, theme.tag_bg) >= focusTintFloor(theme)); - // And its text still reads. - const ink = theme.tag_active_fg orelse theme.tag_fg; - try std.testing.expect(contrast(ink, chrome.tag_active_bg) >= @min(contrast(ink, own), 4.5) - 0.01); - } - } -} - -test "every faithful port meets pardes's chrome floors in its own colours, with nothing left to derive" { - const first = comptime indexOfTheme("lapis") + 1; - const last = comptime indexOfTheme("helix"); - for (themes[first..last]) |*th| { - const chrome = ChromeTheme.fromTheme(th); - const page = th.bg.?; - // Written out already adjusted: the run-time lift and push leave - // the file's own values, so what the file says is what is drawn. - try std.testing.expectEqual(th.border.?, chrome.border); - try std.testing.expectEqual(th.tag_active_bg.?, chrome.tag_active_bg); - try std.testing.expect(contrast(th.border.?, page) >= separator_floor); - try std.testing.expect(contrast(th.tag_active_bg.?, th.tag_bg) >= focusTintFloor(th)); - try std.testing.expect(contrast(th.tag_fg, th.tag_bg) >= 4.5); - try std.testing.expect(contrast(th.tag_active_fg.?, th.tag_active_bg.?) >= 4.5); - try std.testing.expect(contrast(th.box_dim, th.tag_bg) >= 1.5); - try std.testing.expect(th.palette != null); - // A status bar of its own reads as tag text does; without one the - // tagline is the tag's. - try std.testing.expect(contrast(chrome.tagline_fg, chrome.tagline_bg) >= 4.5); - if (th.tagline_bg == null) try std.testing.expectEqual(th.tag_bg, chrome.tagline_bg); - } -} - -test "a derived separator or tint keeps the theme's own when it already stands off" { - const forge = &themes[ - for (themes[0..native_count], 0..) |t, i| { - if (std.mem.eql(u8, t.name, "forge")) break i; - } else unreachable - ]; - const chrome = ChromeTheme.fromTheme(forge); - try std.testing.expectEqual(forge.border.?, chrome.border); - // forge's own tint is 1.23:1 off its tag: pushed on the way it leans. - try std.testing.expect(!std.meta.eql(forge.tag_active_bg.?, chrome.tag_active_bg)); - for (chrome.tag_active_bg, forge.tag_active_bg.?, forge.tag_bg) |pushed, own, plain| - try std.testing.expect(pushed >= own and own >= plain); -} - /// sRGB bytes to OKLab and back (Björn Ottosson's), and a mix in it. fn toOklab(rgb: [3]u8) [3]f32 { var l: [3]f32 = undefined; @@ -258,20 +204,6 @@ pub fn nameTintFloor(ink: [3]u8, ground: [3]u8) f32 { return @min(4.5, contrast(ink, ground) - 0.5); } -test "an OKLab fade holds its ends exactly and keeps a mid-way bright" { - for ([_][3]u8{ .{ 0, 0, 0 }, .{ 255, 255, 255 }, .{ 0x0c, 0x0c, 0x0e }, .{ 0xe8, 0xc4, 0x6a }, .{ 0x1c, 0x51, 0x72 } }) |rgb| { - try std.testing.expectEqual(rgb, fromOklab(toOklab(rgb))); - try std.testing.expectEqual(rgb, mixOklab(rgb, .{ 10, 200, 30 }, 0)); - } - // Red to green through sRGB bytes dips dark at the middle; through - // OKLab it keeps its lightness. - const red: [3]u8 = .{ 255, 0, 0 }; - const green: [3]u8 = .{ 0, 200, 0 }; - const srgb_mid = mix(red, green); - const lab_mid = mixOklab(red, green, 0.5); - try std.testing.expect(relativeLuminance(lab_mid) > relativeLuminance(srgb_mid) * 1.3); -} - pub fn mix(a: [3]u8, b: [3]u8) [3]u8 { var out: [3]u8 = undefined; for (&out, a, b) |*c, x, y| c.* = @intCast((@as(u16, x) + y) / 2); @@ -506,31 +438,6 @@ pub fn groupAt(index: usize) ?[]const u8 { return null; } -test "the picker's sections run in ring order and cover it" { - var last: usize = 0; - inline for (theme_groups, 0..) |g, n| { - const at = comptime indexOfTheme(g.first); - if (n == 0) try std.testing.expectEqual(@as(usize, 0), at) else try std.testing.expect(at > last); - last = at; - } - try std.testing.expectEqualStrings("Pardes themes", groupAt(0).?); - // acme is a current theme, not a legacy one. - try std.testing.expect(indexOfTheme("acme") < indexOfTheme("helix")); - try std.testing.expect(groupAt(native_count) != null); -} - -test "seoul256's twelve backgrounds ring in their order, after Catppuccin and before Zenbones" { - const names = [_][]const u8{ - "seoul256_dark_233", "seoul256_dark_234", "seoul256_dark_235", "seoul256_dark_236", - "seoul256_dark_237", "seoul256_dark_238", "seoul256_dark_239", "seoul256_light_252", - "seoul256_light_253", "seoul256_light_254", "seoul256_light_255", "seoul256_light_256", - }; - const first = indexOfTheme("seoul256_dark_233"); - for (names, themes[first..][0..names.len]) |name, t| try std.testing.expectEqualStrings(name, t.name); - try std.testing.expectEqualStrings("catppuccin_mocha", themes[first - 1].name); - try std.testing.expectEqualStrings("zenbones_light", themes[first + names.len].name); -} - /// Original and classic-inspired Pardes palettes precede retained imports. pub const native_theme_count = 15; @@ -793,17 +700,6 @@ fn putName(w: *std.Io.Writer, cap: usize, name: []const u8) bool { return true; } -test "a theme hint drops whole names to fit, never cutting one" { - var buf: [23]u8 = undefined; - const said = themesNear(&buf, "9dracula"); - var words = std.mem.tokenizeScalar(u8, said, ' '); - while (words.next()) |word| { - var whole = false; - for (themes) |t| whole = whole or std.mem.eql(u8, t.name, word); - try std.testing.expect(whole); - } -} - fn likeness(theme_name: []const u8, name: []const u8) usize { var prefix: usize = 0; while (prefix < @min(theme_name.len, name.len) and std.ascii.toLower(theme_name[prefix]) == std.ascii.toLower(name[prefix])) prefix += 1; @@ -845,6 +741,110 @@ pub fn setThemeIndex(p: *Pardes, index: usize) void { p.settings.theme = @intCast(index); } +test "every native theme's separators stand off its page, and its focus tint off its tag" { + for (themes[0..native_count]) |*theme| { + const chrome = ChromeTheme.fromTheme(theme); + const page = theme.bg orelse null_page; + try std.testing.expect(contrast(chrome.border, page) >= separator_floor); + // A dark page's focused tag is told by its band too, not the grip + // alone; acme's (light, and acme's own) is told by its button. + if (relativeLuminance(page) < 0.18) try std.testing.expect(theme.tag_active_bg != null); + if (theme.tag_active_bg) |own| { + try std.testing.expect(contrast(chrome.tag_active_bg, theme.tag_bg) >= focusTintFloor(theme)); + // And its text still reads. + const ink = theme.tag_active_fg orelse theme.tag_fg; + try std.testing.expect(contrast(ink, chrome.tag_active_bg) >= @min(contrast(ink, own), 4.5) - 0.01); + } + } +} + +test "every faithful port meets pardes's chrome floors in its own colours, with nothing left to derive" { + const first = comptime indexOfTheme("lapis") + 1; + const last = comptime indexOfTheme("helix"); + for (themes[first..last]) |*th| { + const chrome = ChromeTheme.fromTheme(th); + const page = th.bg.?; + // Written out already adjusted: the run-time lift and push leave + // the file's own values, so what the file says is what is drawn. + try std.testing.expectEqual(th.border.?, chrome.border); + try std.testing.expectEqual(th.tag_active_bg.?, chrome.tag_active_bg); + try std.testing.expect(contrast(th.border.?, page) >= separator_floor); + try std.testing.expect(contrast(th.tag_active_bg.?, th.tag_bg) >= focusTintFloor(th)); + try std.testing.expect(contrast(th.tag_fg, th.tag_bg) >= 4.5); + try std.testing.expect(contrast(th.tag_active_fg.?, th.tag_active_bg.?) >= 4.5); + try std.testing.expect(contrast(th.box_dim, th.tag_bg) >= 1.5); + try std.testing.expect(th.palette != null); + // A status bar of its own reads as tag text does; without one the + // tagline is the tag's. + try std.testing.expect(contrast(chrome.tagline_fg, chrome.tagline_bg) >= 4.5); + if (th.tagline_bg == null) try std.testing.expectEqual(th.tag_bg, chrome.tagline_bg); + } +} + +test "a derived separator or tint keeps the theme's own when it already stands off" { + const forge = &themes[ + for (themes[0..native_count], 0..) |t, i| { + if (std.mem.eql(u8, t.name, "forge")) break i; + } else unreachable + ]; + const chrome = ChromeTheme.fromTheme(forge); + try std.testing.expectEqual(forge.border.?, chrome.border); + // forge's own tint is 1.23:1 off its tag: pushed on the way it leans. + try std.testing.expect(!std.meta.eql(forge.tag_active_bg.?, chrome.tag_active_bg)); + for (chrome.tag_active_bg, forge.tag_active_bg.?, forge.tag_bg) |pushed, own, plain| + try std.testing.expect(pushed >= own and own >= plain); +} + +test "an OKLab fade holds its ends exactly and keeps a mid-way bright" { + for ([_][3]u8{ .{ 0, 0, 0 }, .{ 255, 255, 255 }, .{ 0x0c, 0x0c, 0x0e }, .{ 0xe8, 0xc4, 0x6a }, .{ 0x1c, 0x51, 0x72 } }) |rgb| { + try std.testing.expectEqual(rgb, fromOklab(toOklab(rgb))); + try std.testing.expectEqual(rgb, mixOklab(rgb, .{ 10, 200, 30 }, 0)); + } + // Red to green through sRGB bytes dips dark at the middle; through + // OKLab it keeps its lightness. + const red: [3]u8 = .{ 255, 0, 0 }; + const green: [3]u8 = .{ 0, 200, 0 }; + const srgb_mid = mix(red, green); + const lab_mid = mixOklab(red, green, 0.5); + try std.testing.expect(relativeLuminance(lab_mid) > relativeLuminance(srgb_mid) * 1.3); +} + +test "the picker's sections run in ring order and cover it" { + var last: usize = 0; + inline for (theme_groups, 0..) |g, n| { + const at = comptime indexOfTheme(g.first); + if (n == 0) try std.testing.expectEqual(@as(usize, 0), at) else try std.testing.expect(at > last); + last = at; + } + try std.testing.expectEqualStrings("Pardes themes", groupAt(0).?); + // acme is a current theme, not a legacy one. + try std.testing.expect(indexOfTheme("acme") < indexOfTheme("helix")); + try std.testing.expect(groupAt(native_count) != null); +} + +test "seoul256's twelve backgrounds ring in their order, after Catppuccin and before Zenbones" { + const names = [_][]const u8{ + "seoul256_dark_233", "seoul256_dark_234", "seoul256_dark_235", "seoul256_dark_236", + "seoul256_dark_237", "seoul256_dark_238", "seoul256_dark_239", "seoul256_light_252", + "seoul256_light_253", "seoul256_light_254", "seoul256_light_255", "seoul256_light_256", + }; + const first = indexOfTheme("seoul256_dark_233"); + for (names, themes[first..][0..names.len]) |name, t| try std.testing.expectEqualStrings(name, t.name); + try std.testing.expectEqualStrings("catppuccin_mocha", themes[first - 1].name); + try std.testing.expectEqualStrings("zenbones_light", themes[first + names.len].name); +} + +test "a theme hint drops whole names to fit, never cutting one" { + var buf: [23]u8 = undefined; + const said = themesNear(&buf, "9dracula"); + var words = std.mem.tokenizeScalar(u8, said, ' '); + while (words.next()) |word| { + var whole = false; + for (themes) |t| whole = whole or std.mem.eql(u8, t.name, word); + try std.testing.expect(whole); + } +} + test "a theme file that cannot be read is named in the failure" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); diff --git a/src/config.zig b/src/config.zig index b9ddf07a..96a5f557 100644 --- a/src/config.zig +++ b/src/config.zig @@ -174,52 +174,6 @@ pub const leader_path = paths: { break :paths table; }; -test "Space-k is unbound while Exit, Kill and other k chords remain available" { - try std.testing.expect(leader_path.get(.Kill) == null); - try std.testing.expectEqualStrings("q", leader_path.get(.Exit).?); - try std.testing.expectEqualStrings("w", leader_path.get(.Window).?); - try std.testing.expectEqualStrings("lk", leader_path.get(.Hover).?); - try std.testing.expectEqualStrings("d", leader_path.get(.Del).?); - for (pardes.builtin_rows) |row| if (row.cmd == .Kill) { - try std.testing.expect(row.path == null); - try std.testing.expect(std.mem.indexOf(u8, row.line, "SPC") == null); - try std.testing.expect(std.mem.indexOf(u8, row.line, "Kill") != null); - }; - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("first\nsecond\n"); - pane.body.cur_row = 1; - while (p.nextEffect()) |_| {} - p.update(.{ .key = .{ .cp = ' ' } }); - try std.testing.expect(p.view().prefix == .leader); - p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expect(p.view().prefix != .leader and !p.quit); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); - while (p.nextEffect()) |effect| try std.testing.expect(effect != .quit); - p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); - // Kill stops commands and never quits; Exit quits. - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Kill")); - try std.testing.expect(!p.quit); - try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); - try std.testing.expect(p.quit); -} - -test "SPC q runs Exit: refused once over unsaved text, as the tag word is, then it quits" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("text\n"); - pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified - pane.file.?.saved_hash = 0; // edited: what it had is not what it has - while (p.nextEffect()) |_| {} - p.update(.{ .key = .{ .cp = ' ' } }); - p.update(.{ .key = .{ .cp = 'q' } }); - try std.testing.expect(!p.quit); - p.update(.{ .key = .{ .cp = ' ' } }); - p.update(.{ .key = .{ .cp = 'q' } }); - try std.testing.expect(p.quit); -} - pub const look_key: []const Chord = &.{.{ .cp = Key.enter }}; pub const exec_key: []const Chord = &.{.{ .cp = Key.tab }}; pub const look_button: Mouse.Button = .right; @@ -372,20 +326,6 @@ pub fn wheelTick(guard: *u8, vertical: bool) bool { return false; } -test "wheel drift guard" { - var g: u8 = 0; - try std.testing.expect(wheelTick(&g, false)); - try std.testing.expect(wheelTick(&g, false)); - if (wheel_guard_ticks == 0) return; // guard disabled: nothing left to check - for (0..4) |_| try std.testing.expect(wheelTick(&g, true)); - try std.testing.expect(!wheelTick(&g, false)); - try std.testing.expect(wheelTick(&g, true)); - try std.testing.expect(!wheelTick(&g, false)); - for (1..wheel_guard_ticks) |_| try std.testing.expect(!wheelTick(&g, false)); - try std.testing.expect(wheelTick(&g, false)); - try std.testing.expect(wheelTick(&g, false)); -} - /// The shell when no `Shell` is set: the user's login shell ($SHELL), as a /// terminal would start, else /bin/sh. An explicit `Shell` overrides it. pub fn defaultShell() []const u8 { @@ -1463,11 +1403,6 @@ pub const User = struct { } }; -test { - _ = Runtime; - _ = User; -} - /// The docs in docs/typ name words, keys and tags; each must still be here. const doc_typ = struct { /// The leading string arguments of every `name("...", "...")` call in a @@ -1622,37 +1557,6 @@ const doc_typ = struct { } }; -test "docs/typ names only words, keys and default tags that exist" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const gpa = arena.allocator(); - const io = std.testing.io; - var dir = try std.Io.Dir.cwd().openDir(io, @import("doc_typ").dir, .{ .iterate = true }); - defer dir.close(io); - var found: [3]std.ArrayList([]const u8) = @splat(.empty); - // The arena's: gone with this test, so no later test reads it. - defer doc_typ.other_build = ""; - defer doc_typ.addon_sources = ""; - try doc_typ.loadAddons(gpa); - for ([_][]const u8{ "builtins-tui.json", "builtins-gui.json" }) |f| { - const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue; - doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text }); - } - var it = dir.iterate(); - while (try it.next(io)) |entry| if (entry.kind == .file and std.mem.endsWith(u8, entry.name, ".typ")) { - const source = try dir.readFileAlloc(io, entry.name, gpa, .limited(1 << 20)); - inline for (.{ "word", "key", "tag" }, &found) |name, *list| try doc_typ.calls(gpa, source, name, list); - try doc_typ.calls(gpa, source, "keys", &found[1]); // alternatives, each a key - }; - inline for (.{ "word", "key", "tag" }, found) |name, list| { - try std.testing.expect(list.items.len >= 5); - for (list.items) |arg| if (!@field(doc_typ, name)(arg)) { - std.debug.print("docs/typ: {s}(\"{s}\") is not in pardes\n", .{ name, arg }); - return error.DocDrift; - }; - } -} - /// The tutor's own spellings, which the docs/typ test cannot read: a /// builtin in backticks (`Save`, `Kill make`), a tag on a line of its own /// after "| ", a leader path after SPC (`SPC f s`), a chord as Ctrl-, Alt- @@ -1729,6 +1633,102 @@ const doc_tutor = struct { } }; +test "Space-k is unbound while Exit, Kill and other k chords remain available" { + try std.testing.expect(leader_path.get(.Kill) == null); + try std.testing.expectEqualStrings("q", leader_path.get(.Exit).?); + try std.testing.expectEqualStrings("w", leader_path.get(.Window).?); + try std.testing.expectEqualStrings("lk", leader_path.get(.Hover).?); + try std.testing.expectEqualStrings("d", leader_path.get(.Del).?); + for (pardes.builtin_rows) |row| if (row.cmd == .Kill) { + try std.testing.expect(row.path == null); + try std.testing.expect(std.mem.indexOf(u8, row.line, "SPC") == null); + try std.testing.expect(std.mem.indexOf(u8, row.line, "Kill") != null); + }; + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("first\nsecond\n"); + pane.body.cur_row = 1; + while (p.nextEffect()) |_| {} + p.update(.{ .key = .{ .cp = ' ' } }); + try std.testing.expect(p.view().prefix == .leader); + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expect(p.view().prefix != .leader and !p.quit); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + while (p.nextEffect()) |effect| try std.testing.expect(effect != .quit); + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + // Kill stops commands and never quits; Exit quits. + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Kill")); + try std.testing.expect(!p.quit); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Exit")); + try std.testing.expect(p.quit); +} + +test "SPC q runs Exit: refused once over unsaved text, as the tag word is, then it quits" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("text\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + while (p.nextEffect()) |_| {} + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'q' } }); + try std.testing.expect(!p.quit); + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'q' } }); + try std.testing.expect(p.quit); +} + +test "wheel drift guard" { + var g: u8 = 0; + try std.testing.expect(wheelTick(&g, false)); + try std.testing.expect(wheelTick(&g, false)); + if (wheel_guard_ticks == 0) return; // guard disabled: nothing left to check + for (0..4) |_| try std.testing.expect(wheelTick(&g, true)); + try std.testing.expect(!wheelTick(&g, false)); + try std.testing.expect(wheelTick(&g, true)); + try std.testing.expect(!wheelTick(&g, false)); + for (1..wheel_guard_ticks) |_| try std.testing.expect(!wheelTick(&g, false)); + try std.testing.expect(wheelTick(&g, false)); + try std.testing.expect(wheelTick(&g, false)); +} + +test { + _ = Runtime; + _ = User; +} + +test "docs/typ names only words, keys and default tags that exist" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + const io = std.testing.io; + var dir = try std.Io.Dir.cwd().openDir(io, @import("doc_typ").dir, .{ .iterate = true }); + defer dir.close(io); + var found: [3]std.ArrayList([]const u8) = @splat(.empty); + // The arena's: gone with this test, so no later test reads it. + defer doc_typ.other_build = ""; + defer doc_typ.addon_sources = ""; + try doc_typ.loadAddons(gpa); + for ([_][]const u8{ "builtins-tui.json", "builtins-gui.json" }) |f| { + const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue; + doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text }); + } + var it = dir.iterate(); + while (try it.next(io)) |entry| if (entry.kind == .file and std.mem.endsWith(u8, entry.name, ".typ")) { + const source = try dir.readFileAlloc(io, entry.name, gpa, .limited(1 << 20)); + inline for (.{ "word", "key", "tag" }, &found) |name, *list| try doc_typ.calls(gpa, source, name, list); + try doc_typ.calls(gpa, source, "keys", &found[1]); // alternatives, each a key + }; + inline for (.{ "word", "key", "tag" }, found) |name, list| { + try std.testing.expect(list.items.len >= 5); + for (list.items) |arg| if (!@field(doc_typ, name)(arg)) { + std.debug.print("docs/typ: {s}(\"{s}\") is not in pardes\n", .{ name, arg }); + return error.DocDrift; + }; + } +} + test "the tutor names only words, keys, paths and default tags that exist" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/src/diff.zig b/src/diff.zig index 842a6b41..ed54c149 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -405,14 +405,6 @@ pub fn targetAt(lines: []const []const u8, row: usize, continued_rows: bool) ?Ta const testing = std.testing; -fn splitLines(comptime text: []const u8) [std.mem.count(u8, text, "\n")][]const u8 { - @setEvalBranchQuota(100_000); - var out: [std.mem.count(u8, text, "\n")][]const u8 = undefined; - var it = std.mem.splitScalar(u8, text, '\n'); - for (&out) |*line| line.* = it.next().?; - return out; -} - const git_diff = \\diff --git a/src/a.zig b/src/a.zig \\index 1111111..2222222 100644 @@ -439,6 +431,22 @@ const git_diff = \\ ; +fn splitLines(comptime text: []const u8) [std.mem.count(u8, text, "\n")][]const u8 { + @setEvalBranchQuota(100_000); + var out: [std.mem.count(u8, text, "\n")][]const u8 = undefined; + var it = std.mem.splitScalar(u8, text, '\n'); + for (&out) |*line| line.* = it.next().?; + return out; +} + +fn pathsOf(comptime text: []const u8) ![3][]const u8 { + const lines = splitLines(text); + var w: Walk = .{}; + for (lines) |line| _ = w.step(line); + const t = targetAt(&lines, 3, false) orelse return error.NoTarget; + return .{ w.old_path, w.new_path, t.path }; +} + test "diff every line of a section that deletes its file is about a file this diff deletes" { const lines = splitLines(git_diff); var rows: usize = 0; @@ -623,14 +631,6 @@ test "diff git's side prefixes: dropped when both sides carry different ones, el try testing.expect(gitHeader("diff -u old new") == null); } -fn pathsOf(comptime text: []const u8) ![3][]const u8 { - const lines = splitLines(text); - var w: Walk = .{}; - for (lines) |line| _ = w.step(line); - const t = targetAt(&lines, 3, false) orelse return error.NoTarget; - return .{ w.old_path, w.new_path, t.path }; -} - test "diff a section's paths are the repository's names under every prefix git writes, and as written elsewhere" { const expect = struct { fn paths(got: [3][]const u8, old: []const u8, new: []const u8) !void { diff --git a/src/dump.zig b/src/dump.zig index 9849c8e4..82b55ae6 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -57,14 +57,6 @@ pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; } -test "a DumpDir reads back absolute, however it was written" { - var buf: [4096]u8 = undefined; - try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp/dumps/").?); - try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp//x/../dumps").?); - const rel = directory(&buf, "rel/"); - try std.testing.expect(std.Io.Dir.path.isAbsolute(rel.?) and std.mem.endsWith(u8, rel.?, "/rel")); -} - /// The standard dump directory, without creating it or generating a filename. pub fn defaultDirectory(buf: []u8) ?[]const u8 { if (hostEnv("XDG_DATA_HOME")) |x| @@ -696,6 +688,149 @@ pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane { return pane; } +// ---- a pane of a kind (Kind.Slot) ---- + +/// What a dump keeps of a pane of a kind: the kind, its path, its place, +/// the art bytes, its words' last values, whether its kind was here, and +/// the kind's own record when it has one. +const SlotRecord = struct { + name: []const u8 = "", + version: u32 = 0, + path: []const u8 = "", + where: []const u8 = "", + art: @import("surface.zig").Placement.Art = .{}, + record: ?[]const u8 = null, + values: []const u8 = "", + live: bool = false, + /// What decides its next calls (Kind.step): a replica joining keeps + /// them, its Shadow calling where the authority's kind does. + next_tick: u64 = 0, + views: [views.max]u64 = @splat(0), + focused: bool = false, + /// The jobs whose answers it dropped (api.cancel): a replica's drop them too. + cancelled: [4]u32 = @splat(0), + /// Its tick's prefix: a replica's tag laid out as the session's. + prefix: []const u8 = "", + /// A placeholder's why (its file not here). + refused: []const u8 = "", + /// What a step reads of it that its kind's open made (Kind.reopen) or + /// a call set: its tag's default words and what it has selected. A + /// replica's load opens no kind; without them its tag wrapped another + /// way and its yank took nothing. + tail: []const u8 = "", + selection: []const u8 = "", +}; + +pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { + var place: [32]u8 = undefined; + var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .views = s.views, .focused = s.focused, .cancelled = s.cancelled, .prefix = s.prefix.slice(), .refused = s.refused.slice(), .tail = s.tail.slice(), .selection = s.selection }; + var owned: ?[]u8 = null; + defer if (owned) |o| s.gpa.free(o); + if (s.ops != null) { + r.where = Kind.where(@constCast(s), &place); + owned = try slotRecord(@constCast(s)); + r.record = owned; + } + const bytes = try walk.save(SlotRecord, gpa, &r); + defer gpa.free(bytes); + try w.writeAll(bytes); +} + +/// The kind's record of a slot's state (`s.gpa`'s), or null for none: at +/// most PA_RECORD_MAX bytes. +pub fn slotRecord(s: *Kind.Slot) !?[]u8 { + const f = (s.ops orelse return null).dump orelse return null; + const buf = try s.gpa.alloc(u8, Kind.c.PA_RECORD_MAX); + const n = Kind.dumpCall(s, f, buf); + if (n == 0 or n > buf.len) { + s.gpa.free(buf); + return null; + } + return s.gpa.realloc(buf, n) catch buf[0..n]; +} + +/// The pane back from its record, a placeholder holding it until its +/// kind opens it (`revivePane`; a replica's core keeps it a Shadow). +pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !void { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const r = try walk.load(SlotRecord, arena.allocator(), bytes, null); + out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art, .live = r.live, .next_tick = r.next_tick, .views = r.views, .focused = r.focused, .cancelled = r.cancelled }; + errdefer out.free(); + @memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]); + out.path = try gpa.dupe(u8, r.path); + out.where_text.set(r.where); + out.prefix.set(r.prefix); + out.refused.set(r.refused); + out.tail.set(r.tail); + out.values.set(r.values); + out.selection = try gpa.dupe(u8, r.selection); + if (r.record) |rec| out.record = try gpa.dupe(u8, rec); +} + +pub fn slotFree(s: *Kind.Slot, gpa: std.mem.Allocator) void { + _ = gpa; + s.free(); +} + +/// A loaded pane of a kind opened by its kind from its file as a Look +/// reads it, then given its record, if this core has the kind; else, or +/// refused (its file not here, its record not taken), a placeholder saying +/// what it waits for, its record kept. One with no record reopens at its +/// place with its words. A placeholder comes back at the next Look or +/// watch of its path, or the load of its kind. +pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void { + const k = p.kinds.byName(s.nameOf()) orelse { + s.live = false; + return; + }; + s.ops = p.kinds.ops[k]; + s.gen = p.kinds.kinds[k].gen; + // A replica has no code to read it for: the authority's outcome is taped. + const bytes: ?[]u8 = if (s.ops != null and s.path.len > 0) filesystem.read(p, s.path) catch null else null; + defer if (bytes) |b| p.gpa.free(b); + const kept = .{ s.next_tick, s.views, s.focused }; + if (!Kind.reopen(p, id, s, bytes)) { + s.ops = null; + s.live = false; + } else if (s.ops == null) { + // A replica's Shadow is the authority's pane as it is: it ticks + // when that one does, not because it was loaded (a kind opened + // here ticks to lay itself out). + s.next_tick, s.views, s.focused = kept; + } +} + +/// A PDF pane of a dump from before the pdf addon: a pane of the addon's +/// kind `pdf` on its file, at its page, its fit and tint given again as +/// its words; a placeholder until the addon is loaded. +fn revivePdf(p: *Pardes, id: usize, pane: *pardes.panes.Pane, old: *pardes.panes.Pane.LegacyPdf) void { + defer { + p.image_gpa.free(old.path); + p.image_gpa.destroy(old); + pane.pdf = null; + } + const s = p.image_gpa.create(Kind.Slot) catch return; + s.* = .{ .gpa = p.image_gpa, .arena = .init(p.image_gpa), .version = 1, .live = true }; + @memcpy(s.name[0..3], "pdf"); + s.path = p.image_gpa.dupe(u8, old.path) catch { + s.free(); + return p.image_gpa.destroy(s); + }; + _ = s.where_text.print("{d}", .{old.page + 1}); + _ = s.values.print("PdfFit {t}\nPdfTint {t}\n", .{ old.fit, old.tint }); + pane.addon = s; + reviveSlot(p, id, s); +} + +test "a DumpDir reads back absolute, however it was written" { + var buf: [4096]u8 = undefined; + try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp/dumps/").?); + try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp//x/../dumps").?); + const rel = directory(&buf, "rel/"); + try std.testing.expect(std.Io.Dir.path.isAbsolute(rel.?) and std.mem.endsWith(u8, rel.?, "/rel")); +} + test "a dump keeps the session's settings, and a restore applies them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); @@ -814,7 +949,7 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa const text = try term.screenTextAlloc(q.panes[0].?, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "one\ntwo\n") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "two") .? < std.mem.indexOf(u8, text, "restored history").?); + try std.testing.expect(std.mem.indexOf(u8, text, "two").? < std.mem.indexOf(u8, text, "restored history").?); } test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" { @@ -939,138 +1074,3 @@ test "an old dump's file, a byte dump, is read by -l and by a Restore of its pat defer gpa.free(again); try std.testing.expectEqualSlices(u8, bytes, again); } - -// ---- a pane of a kind (Kind.Slot) ---- - -/// What a dump keeps of a pane of a kind: the kind, its path, its place, -/// the art bytes, its words' last values, whether its kind was here, and -/// the kind's own record when it has one. -const SlotRecord = struct { - name: []const u8 = "", - version: u32 = 0, - path: []const u8 = "", - where: []const u8 = "", - art: @import("surface.zig").Placement.Art = .{}, - record: ?[]const u8 = null, - values: []const u8 = "", - live: bool = false, - /// What decides its next calls (Kind.step): a replica joining keeps - /// them, its Shadow calling where the authority's kind does. - next_tick: u64 = 0, - views: [views.max]u64 = @splat(0), - focused: bool = false, - /// The jobs whose answers it dropped (api.cancel): a replica's drop them too. - cancelled: [4]u32 = @splat(0), - /// Its tick's prefix: a replica's tag laid out as the session's. - prefix: []const u8 = "", - /// A placeholder's why (its file not here). - refused: []const u8 = "", - /// What a step reads of it that its kind's open made (Kind.reopen) or - /// a call set: its tag's default words and what it has selected. A - /// replica's load opens no kind; without them its tag wrapped another - /// way and its yank took nothing. - tail: []const u8 = "", - selection: []const u8 = "", -}; - -pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { - var place: [32]u8 = undefined; - var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .views = s.views, .focused = s.focused, .cancelled = s.cancelled, .prefix = s.prefix.slice(), .refused = s.refused.slice(), .tail = s.tail.slice(), .selection = s.selection }; - var owned: ?[]u8 = null; - defer if (owned) |o| s.gpa.free(o); - if (s.ops != null) { - r.where = Kind.where(@constCast(s), &place); - owned = try slotRecord(@constCast(s)); - r.record = owned; - } - const bytes = try walk.save(SlotRecord, gpa, &r); - defer gpa.free(bytes); - try w.writeAll(bytes); -} - -/// The kind's record of a slot's state (`s.gpa`'s), or null for none: at -/// most PA_RECORD_MAX bytes. -pub fn slotRecord(s: *Kind.Slot) !?[]u8 { - const f = (s.ops orelse return null).dump orelse return null; - const buf = try s.gpa.alloc(u8, Kind.c.PA_RECORD_MAX); - const n = Kind.dumpCall(s, f, buf); - if (n == 0 or n > buf.len) { - s.gpa.free(buf); - return null; - } - return s.gpa.realloc(buf, n) catch buf[0..n]; -} - -/// The pane back from its record, a placeholder holding it until its -/// kind opens it (`revivePane`; a replica's core keeps it a Shadow). -pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !void { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const r = try walk.load(SlotRecord, arena.allocator(), bytes, null); - out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art, .live = r.live, .next_tick = r.next_tick, .views = r.views, .focused = r.focused, .cancelled = r.cancelled }; - errdefer out.free(); - @memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]); - out.path = try gpa.dupe(u8, r.path); - out.where_text.set(r.where); - out.prefix.set(r.prefix); - out.refused.set(r.refused); - out.tail.set(r.tail); - out.values.set(r.values); - out.selection = try gpa.dupe(u8, r.selection); - if (r.record) |rec| out.record = try gpa.dupe(u8, rec); -} - -pub fn slotFree(s: *Kind.Slot, gpa: std.mem.Allocator) void { - _ = gpa; - s.free(); -} - -/// A loaded pane of a kind opened by its kind from its file as a Look -/// reads it, then given its record, if this core has the kind; else, or -/// refused (its file not here, its record not taken), a placeholder saying -/// what it waits for, its record kept. One with no record reopens at its -/// place with its words. A placeholder comes back at the next Look or -/// watch of its path, or the load of its kind. -pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void { - const k = p.kinds.byName(s.nameOf()) orelse { - s.live = false; - return; - }; - s.ops = p.kinds.ops[k]; - s.gen = p.kinds.kinds[k].gen; - // A replica has no code to read it for: the authority's outcome is taped. - const bytes: ?[]u8 = if (s.ops != null and s.path.len > 0) filesystem.read(p, s.path) catch null else null; - defer if (bytes) |b| p.gpa.free(b); - const kept = .{ s.next_tick, s.views, s.focused }; - if (!Kind.reopen(p, id, s, bytes)) { - s.ops = null; - s.live = false; - } else if (s.ops == null) { - // A replica's Shadow is the authority's pane as it is: it ticks - // when that one does, not because it was loaded (a kind opened - // here ticks to lay itself out). - s.next_tick, s.views, s.focused = kept; - } -} - -/// A PDF pane of a dump from before the pdf addon: a pane of the addon's -/// kind `pdf` on its file, at its page, its fit and tint given again as -/// its words; a placeholder until the addon is loaded. -fn revivePdf(p: *Pardes, id: usize, pane: *pardes.panes.Pane, old: *pardes.panes.Pane.LegacyPdf) void { - defer { - p.image_gpa.free(old.path); - p.image_gpa.destroy(old); - pane.pdf = null; - } - const s = p.image_gpa.create(Kind.Slot) catch return; - s.* = .{ .gpa = p.image_gpa, .arena = .init(p.image_gpa), .version = 1, .live = true }; - @memcpy(s.name[0..3], "pdf"); - s.path = p.image_gpa.dupe(u8, old.path) catch { - s.free(); - return p.image_gpa.destroy(s); - }; - _ = s.where_text.print("{d}", .{old.page + 1}); - _ = s.values.print("PdfFit {t}\nPdfTint {t}\n", .{ old.fit, old.tint }); - pane.addon = s; - reviveSlot(p, id, s); -} diff --git a/src/edit.zig b/src/edit.zig index 064f0f44..3de16c34 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -1900,6 +1900,98 @@ pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, bod }; } +/// acme's double-click (plan9port acme text.c:1407, textdoubleclick): from +/// the point `q` (before the character clicked), the text up to the match +/// of a bracket just before it or just after it (text.c:1386, `{[(<«` and +/// their closers), the whole line at a line's start or end, the quoted text +/// next to `' " \``, else the word, acme's isalnum (util.c:328) run. +pub fn doubleClickRange(text: []const u8, q_in: usize) [2]usize { + const sets = [_][2][]const u21{ + .{ &.{ '{', '[', '(', '<', 0xab }, &.{ '}', ']', ')', '>', 0xbb } }, + .{ &.{'\n'}, &.{'\n'} }, + .{ &.{ '\'', '"', '`' }, &.{ '\'', '"', '`' } }, + }; + const q = @min(q_in, text.len); + for (sets) |set| { + const left, const right = set; + // the character to the left, looking right + const before = if (q == 0) .{ @as(u21, '\n'), @as(usize, 0) } else runeBefore(text, q); + if (std.mem.indexOfScalar(u21, left, before[0])) |k| { + var at = q; + if (clickMatch(text, before[0], right[k], true, &at)) { + const closer = if (before[0] == '\n') 0 else runeLen(right[k]); + return .{ q, at - closer }; + } + return .{ q, q }; + } + // the character to the right, looking left + const after = if (q == text.len) @as(u21, '\n') else runeAt(text, q); + if (std.mem.indexOfScalar(u21, right, after)) |k| { + var at = q; + if (clickMatch(text, after, left[k], false, &at)) { + const q1 = q + @as(usize, @intFromBool(q < text.len and after == '\n')); + var q0 = at; + if (after != '\n' or at != 0 or (text.len > 0 and text[0] == '\n')) q0 += runeLen(left[k]); + return .{ @min(q0, q1), q1 }; + } + return .{ q, q }; + } + } + var lo = q; + var hi = q; + while (hi < text.len and isAlnum(runeAt(text, hi))) hi += std.unicode.utf8ByteSequenceLength(text[hi]) catch 1; + while (lo > 0 and isAlnum(runeBefore(text, lo)[0])) lo = runeBefore(text, lo)[1]; + return .{ lo, hi }; +} + +/// acme's textclickmatch (text.c:1457): the nesting match of `cl` by `cr` +/// from `q`, leaving `q` just past it (forward) or on it (back). +fn clickMatch(text: []const u8, cl: u21, cr: u21, forward: bool, q: *usize) bool { + var nest: usize = 1; + while (true) { + var c: u21 = undefined; + if (forward) { + if (q.* >= text.len) break; + c = runeAt(text, q.*); + q.* += std.unicode.utf8ByteSequenceLength(text[q.*]) catch 1; + } else { + if (q.* == 0) break; + const b = runeBefore(text, q.*); + q.* = b[1]; + c = b[0]; + } + if (c == cr) { + nest -= 1; + if (nest == 0) return true; + } else if (c == cl) nest += 1; + } + return cl == '\n' and nest == 1; +} + +fn runeLen(c: u21) usize { + return std.unicode.utf8CodepointSequenceLength(c) catch 1; +} + +fn runeAt(text: []const u8, at: usize) u21 { + const n = std.unicode.utf8ByteSequenceLength(text[at]) catch return text[at]; + if (at + n > text.len) return text[at]; + return std.unicode.utf8Decode(text[at..][0..n]) catch text[at]; +} + +/// The rune ending at `at`, and where it starts. +fn runeBefore(text: []const u8, at: usize) struct { u21, usize } { + var s = at - 1; + while (s > 0 and text[s] & 0xC0 == 0x80 and at - s < 4) s -= 1; + return .{ runeAt(text, s), s }; +} + +fn isAlnum(c: u21) bool { + if (c <= ' ') return false; + if (c >= 0x7F and c <= 0xA0) return false; + if (c < 0x80 and std.mem.indexOfScalar(u8, "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~", @intCast(c)) != null) return false; + return true; +} + /// Drain the queue and say whether the shell was asked to do `want`. fn drainedEffect(p: *Pardes, want: std.meta.Tag(Effect)) bool { var seen = false; @@ -2082,98 +2174,6 @@ test "only the SPC clipboard commands cross to the system clipboard" { try std.testing.expect(p.view().clip_pending == null); } -/// acme's double-click (plan9port acme text.c:1407, textdoubleclick): from -/// the point `q` (before the character clicked), the text up to the match -/// of a bracket just before it or just after it (text.c:1386, `{[(<«` and -/// their closers), the whole line at a line's start or end, the quoted text -/// next to `' " \``, else the word, acme's isalnum (util.c:328) run. -pub fn doubleClickRange(text: []const u8, q_in: usize) [2]usize { - const sets = [_][2][]const u21{ - .{ &.{ '{', '[', '(', '<', 0xab }, &.{ '}', ']', ')', '>', 0xbb } }, - .{ &.{'\n'}, &.{'\n'} }, - .{ &.{ '\'', '"', '`' }, &.{ '\'', '"', '`' } }, - }; - const q = @min(q_in, text.len); - for (sets) |set| { - const left, const right = set; - // the character to the left, looking right - const before = if (q == 0) .{ @as(u21, '\n'), @as(usize, 0) } else runeBefore(text, q); - if (std.mem.indexOfScalar(u21, left, before[0])) |k| { - var at = q; - if (clickMatch(text, before[0], right[k], true, &at)) { - const closer = if (before[0] == '\n') 0 else runeLen(right[k]); - return .{ q, at - closer }; - } - return .{ q, q }; - } - // the character to the right, looking left - const after = if (q == text.len) @as(u21, '\n') else runeAt(text, q); - if (std.mem.indexOfScalar(u21, right, after)) |k| { - var at = q; - if (clickMatch(text, after, left[k], false, &at)) { - const q1 = q + @as(usize, @intFromBool(q < text.len and after == '\n')); - var q0 = at; - if (after != '\n' or at != 0 or (text.len > 0 and text[0] == '\n')) q0 += runeLen(left[k]); - return .{ @min(q0, q1), q1 }; - } - return .{ q, q }; - } - } - var lo = q; - var hi = q; - while (hi < text.len and isAlnum(runeAt(text, hi))) hi += std.unicode.utf8ByteSequenceLength(text[hi]) catch 1; - while (lo > 0 and isAlnum(runeBefore(text, lo)[0])) lo = runeBefore(text, lo)[1]; - return .{ lo, hi }; -} - -/// acme's textclickmatch (text.c:1457): the nesting match of `cl` by `cr` -/// from `q`, leaving `q` just past it (forward) or on it (back). -fn clickMatch(text: []const u8, cl: u21, cr: u21, forward: bool, q: *usize) bool { - var nest: usize = 1; - while (true) { - var c: u21 = undefined; - if (forward) { - if (q.* >= text.len) break; - c = runeAt(text, q.*); - q.* += std.unicode.utf8ByteSequenceLength(text[q.*]) catch 1; - } else { - if (q.* == 0) break; - const b = runeBefore(text, q.*); - q.* = b[1]; - c = b[0]; - } - if (c == cr) { - nest -= 1; - if (nest == 0) return true; - } else if (c == cl) nest += 1; - } - return cl == '\n' and nest == 1; -} - -fn runeLen(c: u21) usize { - return std.unicode.utf8CodepointSequenceLength(c) catch 1; -} - -fn runeAt(text: []const u8, at: usize) u21 { - const n = std.unicode.utf8ByteSequenceLength(text[at]) catch return text[at]; - if (at + n > text.len) return text[at]; - return std.unicode.utf8Decode(text[at..][0..n]) catch text[at]; -} - -/// The rune ending at `at`, and where it starts. -fn runeBefore(text: []const u8, at: usize) struct { u21, usize } { - var s = at - 1; - while (s > 0 and text[s] & 0xC0 == 0x80 and at - s < 4) s -= 1; - return .{ runeAt(text, s), s }; -} - -fn isAlnum(c: u21) bool { - if (c <= ' ') return false; - if (c >= 0x7F and c <= 0xA0) return false; - if (c < 0x80 and std.mem.indexOfScalar(u8, "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~", @intCast(c)) != null) return false; - return true; -} - test "double-click selects as acme's does" { const t = "fn foo_bar(a, b) {\n x\n}\n"; const Case = struct { q: usize, want: []const u8 }; diff --git a/src/exec.zig b/src/exec.zig index ee6370bf..35d081fd 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -1201,45 +1201,6 @@ fn columnOf(p: *Pardes, id: usize) usize { return if (layout.findPane(p, id)) |f| f.col else p.view().ncol - 1; } -test "the acme chords act once per selection, not once on the primary" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - // Two selections, each naming a DIFFERENT builtin, so what ran is visible - // in the layout rather than in a shell nobody can read from a test. - const pane = try p.setTestFile("Newcol\nNewcol\n"); - const ranges = [_]modal.Selection{ - .{ .anchor = 0, .head = 6 }, - .{ .anchor = 7, .head = 13 }, - }; - pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - - const before = p.view().ncol; - p.update(.{ .key = .{ .cp = Key.tab } }); // config.exec_key: Exec - // BOTH ran. Before this the chord read the primary range and dropped the - // other cursor, so one keystroke over two cursors made one column. - try std.testing.expectEqual(before + 2, p.view().ncol); - // ...and the chord consumed the selection exactly as it does with one. - try std.testing.expectEqual(@as(u16, 0), p.panes[0].?.body.nsel); -} - -test "a switch clicked with a selection held flips unless the selection says on or off" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const before = p.settings.verbose; - _ = execute(p, p.view().active, withArg(p, "Verbose", "some selected text")); - try std.testing.expectEqual(!before, p.settings.verbose); - _ = execute(p, p.view().active, withArg(p, "Verbose", "on")); - try std.testing.expect(p.settings.verbose); - _ = execute(p, p.view().active, withArg(p, "Verbose", " off\n")); - try std.testing.expect(!p.settings.verbose); - // A word that takes any argument still gets the selection. - try std.testing.expectEqualStrings("Msg some text", withArg(p, "Msg", "some text")); -} - // ---- the words addons bring (Kind.Registry's) ---- /// A line whose first word is an addon's: run, and true; false for one @@ -1288,3 +1249,42 @@ pub fn runWord(p: *Pardes, id: usize, w: *const pardes.Kind.Word, line: []const next.len = @intCast(out.buffered().len); s.values = next; } + +test "the acme chords act once per selection, not once on the primary" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + // Two selections, each naming a DIFFERENT builtin, so what ran is visible + // in the layout rather than in a shell nobody can read from a test. + const pane = try p.setTestFile("Newcol\nNewcol\n"); + const ranges = [_]modal.Selection{ + .{ .anchor = 0, .head = 6 }, + .{ .anchor = 7, .head = 13 }, + }; + pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + + const before = p.view().ncol; + p.update(.{ .key = .{ .cp = Key.tab } }); // config.exec_key: Exec + // BOTH ran. Before this the chord read the primary range and dropped the + // other cursor, so one keystroke over two cursors made one column. + try std.testing.expectEqual(before + 2, p.view().ncol); + // ...and the chord consumed the selection exactly as it does with one. + try std.testing.expectEqual(@as(u16, 0), p.panes[0].?.body.nsel); +} + +test "a switch clicked with a selection held flips unless the selection says on or off" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const before = p.settings.verbose; + _ = execute(p, p.view().active, withArg(p, "Verbose", "some selected text")); + try std.testing.expectEqual(!before, p.settings.verbose); + _ = execute(p, p.view().active, withArg(p, "Verbose", "on")); + try std.testing.expect(p.settings.verbose); + _ = execute(p, p.view().active, withArg(p, "Verbose", " off\n")); + try std.testing.expect(!p.settings.verbose); + // A word that takes any argument still gets the selection. + try std.testing.expectEqualStrings("Msg some text", withArg(p, "Msg", "some text")); +} diff --git a/src/fonts.zig b/src/fonts.zig index 5f036119..48fa7179 100644 --- a/src/fonts.zig +++ b/src/fonts.zig @@ -188,40 +188,6 @@ fn scan( return arena.dupe(Font, found[0..found_len]) catch &.{}; } -test "fallback discovery is unique and preserves candidate priority" { - for (fallback_names, 0..) |name, i| { - try std.testing.expect(name.len != 0); - for (fallback_names[0..i]) |prior| - try std.testing.expect(!std.mem.eql(u8, prior, name)); - } - - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const installed = fallbacks(arena_state.allocator()); - var previous: ?usize = null; - for (installed) |font| { - const rank = for (fallback_names, 0..) |name, i| { - if (std.mem.eql(u8, name, font.name)) break i; - } else return error.UnknownFallback; - if (previous) |p| try std.testing.expect(rank > p); - previous = rank; - } -} - -test "the picker lists every monospace face rather than the first max_fonts" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const installed = list(arena_state.allocator(), null); - // A canary, and only meaningful on a machine that HAS fonts: reaching the - // cap is the silent cut max_fonts is sized against. - try std.testing.expect(installed.len < max_fonts); - // ...and what it does return is sorted. - for (installed, 0..) |font, i| { - try std.testing.expect(font.name.len != 0); - if (i > 0) try std.testing.expect(!std.mem.lessThan(u8, font.name, installed[i - 1].name)); - } -} - /// Is every glyph in this font the same width? The grid is one advance for /// every column, chosen once from 'M', so a proportional font in it has every /// row a different length and the mouse pointing at the wrong character: the @@ -318,6 +284,40 @@ fn writeScratch(path: [:0]const u8, bytes: []const u8) !void { try std.testing.expectEqual(@as(isize, @intCast(bytes.len)), libc.write(fd, bytes.ptr, bytes.len)); } +test "fallback discovery is unique and preserves candidate priority" { + for (fallback_names, 0..) |name, i| { + try std.testing.expect(name.len != 0); + for (fallback_names[0..i]) |prior| + try std.testing.expect(!std.mem.eql(u8, prior, name)); + } + + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const installed = fallbacks(arena_state.allocator()); + var previous: ?usize = null; + for (installed) |font| { + const rank = for (fallback_names, 0..) |name, i| { + if (std.mem.eql(u8, name, font.name)) break i; + } else return error.UnknownFallback; + if (previous) |p| try std.testing.expect(rank > p); + previous = rank; + } +} + +test "the picker lists every monospace face rather than the first max_fonts" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const installed = list(arena_state.allocator(), null); + // A canary, and only meaningful on a machine that HAS fonts: reaching the + // cap is the silent cut max_fonts is sized against. + try std.testing.expect(installed.len < max_fonts); + // ...and what it does return is sorted. + for (installed, 0..) |font, i| { + try std.testing.expect(font.name.len != 0); + if (i > 0) try std.testing.expect(!std.mem.lessThan(u8, font.name, installed[i - 1].name)); + } +} + test "monospaced reads the advances out of a real sfnt layout" { // A whole font in 92 bytes: the header, a two-record table directory, and // an hhea + hmtx that between them say "three glyphs, all 600 units wide". diff --git a/src/fs.zig b/src/fs.zig index 67986a81..5e4f181a 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -287,604 +287,177 @@ pub fn validMountName(name: []const u8) bool { return true; } -test "/os refuses a rename or a mode change as not permitted, in words, and still truncates to zero" { - const p = try th.withFile(std.testing.allocator, "x\n"); - defer p.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "kept.txt", .data = "kept\n" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var node: u64 = os_root; - var parts = std.mem.tokenizeScalar(u8, dir, '/'); - while (parts.next()) |part| node = th.look_up(p, node, part).reply.attr.node; - node = th.look_up(p, node, "kept.txt").reply.attr.node; - for ([_]Req{ - .{ .tag = 1, .op = .setattr, .node = node, .set = .{ .mode = true } }, - .{ .tag = 2, .op = .setattr, .node = node, .set = .{ .name = true }, .data = "moved.txt" }, - }) |req| { - const r = th.call(p, req); - try std.testing.expectEqual(E.PERM, r.errno()); - try std.testing.expectStringStartsWith(r.reply.ename, "permission denied"); - } - try std.testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 3, .op = .setattr, .node = node, .truncate = true }).reply.status); +pub fn isVirtual(path: []const u8) bool { + return std.mem.eql(u8, path, "/virtual") or std.mem.startsWith(u8, path, "/virtual/") or + std.mem.eql(u8, path, "/n") or std.mem.startsWith(u8, path, "/n/"); } -test "mounts own their names and dials and reject duplicate or reserved names" { - const gpa = std.testing.allocator; - var ns: Namespace = .{}; - defer ns.deinit(gpa); - var name = "peer".*; - var dial = "/tmp/peer.sock".*; - try ns.mount(gpa, &name, &dial); - @memset(&name, 'x'); - @memset(&dial, 'x'); - try std.testing.expectEqualStrings("peer", ns.mounts.items[0].name); - try std.testing.expectEqualStrings("/tmp/peer.sock", ns.mounts.items[0].dial); - try std.testing.expectError(error.AlreadyMounted, ns.mount(gpa, "peer", "/tmp/other.sock")); - for ([_][]const u8{ "", ".", "..", "os", "self", "a/b", "with space" }) |bad| - try std.testing.expectError(error.BadMountName, ns.mount(gpa, bad, "/tmp/peer.sock")); - for ([_][]const u8{ "", "a\x00b", "tcp!127.0.0.1!0", "tcp!localhost!564" }) |bad| - try std.testing.expectError(error.BadDial, ns.mount(gpa, "valid", bad)); - for (1..max_mounts) |i| { - var buf: [16]u8 = undefined; - try ns.mount(gpa, try std.fmt.bufPrint(&buf, "peer{d}", .{i}), "/tmp/peer.sock"); - } - try std.testing.expectEqual(max_mounts, ns.mounts.items.len); - try std.testing.expectError(error.TooManyMounts, ns.mount(gpa, "full", "/tmp/peer.sock")); +/// std's `statFile`, but a name with a part over 255 bytes is NameTooLong: +/// std's own takes the kernel's ENAMETOOLONG for that for a bug and panics +/// (Io.Threaded dirStatFileLinux), and such a name comes from anyone who +/// writes one to `name`, `look` or DumpDir. +pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOptions) !std.Io.File.Stat { + var parts = std.mem.tokenizeScalar(u8, path, '/'); + while (parts.next()) |part| if (part.len > 255) return error.NameTooLong; + return std.Io.Dir.cwd().statFile(io, path, options); } -test "mount allocation failures preserve prior mounts and release partial copies" { - const Check = struct { - fn run(gpa: std.mem.Allocator) !void { - var ns: Namespace = .{}; - defer ns.deinit(gpa); - try ns.mount(gpa, "first", "/tmp/first.sock"); - ns.mount(gpa, "second", "/tmp/second.sock") catch |err| { - try std.testing.expectEqual(@as(usize, 1), ns.mounts.items.len); - try std.testing.expectEqualStrings("first", ns.mounts.items[0].name); - try std.testing.expectEqualStrings("/tmp/first.sock", ns.mounts.items[0].dial); - return err; - }; - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{}); +/// Make `dir` and each directory above it that is missing, as `mkdir -p` +/// does: one already there is no failure. A failure shows at the open +/// that follows. +pub fn makeDirs(dir: []const u8) void { + if (comptime !platform_has_fs) return; + if (dir.len == 0) return; + pardes.tape.site(.make_dirs, null, makeDirsHost, .{dir}); } -test "unmount refuses pane paths inherited directories and queued save targets" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try p.fs.mount(gpa, "peer", "/tmp/peer.sock"); - const pane = try p.setTestFile("unsaved\n"); - for ([_][]const u8{ "/n/peer", "/n/peer/file", "/n/peer/dir/file" }) |path| { - gpa.free(pane.file.?.path); - pane.file.?.path = try gpa.dupe(u8, path); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - } - gpa.free(pane.file.?.path); - pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); - const slot = p.freeSlot().?; - const shell = try p.newShell(slot, "/n/peer/dir"); - p.setCwd(slot, "/n/peer/dir"); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - pane.cwd = .{ .inherited = shell }; - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - p.setCwd(slot, "/"); - while (p.nextEffect()) |_| {} - p.emit(.{ .save_text = .{ .pane = 0, .serial = pane.serial, .path = .from("/n/peer/pending") } }); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - while (p.nextEffect()) |_| {} - try unmount(p, "peer"); - try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try std.testing.expectError(error.NotMounted, unmount(p, "peer")); - try p.fs.mount(gpa, "peer", "/tmp/other.sock"); - try std.testing.expectEqualStrings("/tmp/other.sock", p.fs.mounts.items[0].dial); +fn makeDirsHost(dir: []const u8) void { + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; } -test "virtual writes enforce permissions even when contents are empty" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - for ([_][]const u8{ "", "bytes" }) |bytes| { - for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README" }) |path| - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - // /log takes one word, `follow`, and only on the open it changes. - if (bytes.len > 0) if (write(p, "/n/self/log", bytes)) |_| return error.TestUnexpectedResult else |_| {}; - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/pane", bytes)); - try std.testing.expectError(error.FileNotFound, write(p, "/virtual/missing", bytes)); - try std.testing.expectError(error.FileNotFound, write(p, "/virtual/cons", bytes)); - if (limits.embedded_sources) { - for ([_][]const u8{ "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); - } else try std.testing.expectError(error.FileNotFound, write(p, "/virtual/src/fs.zig", bytes)); +/// Whether `dir` is not there to make because one above it refuses: its +/// nearest ancestor that is there may not be searched or written (EACCES: +/// `noperm/a/b`, `/proc/1/root/x`). +pub fn deniedAbove(dir: []const u8) bool { + if (comptime !platform_has_fs) return false; + var at: ?[]const u8 = dir; + while (at) |d| : (at = std.Io.Dir.path.dirname(d)) { + var z: [4096]u8 = undefined; + const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{d}, 0) catch return false; + if (libc.access(dz.ptr, 0) != 0) continue; // F_OK + return libc.access(dz.ptr, 2 | 1) != 0; // W_OK | X_OK } - for (p.fs.opens) |o| try std.testing.expect(o.node == 0); + return false; } -test "direct self reads and writes use the same dot paths as Look" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("old contents\n"); - var path_buf: [256]u8 = undefined; - for ([_][]const u8{ "/virtual", "/n/self" }) |root| { - const path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/{d}/../{d}/body/./", .{ root, pane.serial, pane.serial }); - try write(p, path, "replacement\n"); - try std.testing.expectEqualStrings("replacement\n", pane.file.?.content); - const bytes = try read(p, path); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(pane.file.?.content, bytes); - var resolved: [4096]u8 = undefined; - const canonical = resolve(p, path, "/", &resolved).?; - try std.testing.expectEqual(tree.resolveSelf(p, canonical.path[9..]), tree.resolveSelf(p, path[root.len..])); - try std.testing.expectEqual(@as(?u64, tree.root), tree.resolveSelf(p, "./pane/../../")); - const index_path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/../index", .{root}); - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, index_path, "")); - const index = try read(p, index_path); - defer gpa.free(index); - try std.testing.expect(std.mem.indexOf(u8, index, "/test.txt") != null); - } - var overlong: [4110]u8 = @splat('x'); - @memcpy(overlong[0..9], "/virtual/"); - var resolved: [4096]u8 = undefined; - try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); - try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); - try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); +pub fn localPath(path: []const u8) ?[]const u8 { + if (std.mem.eql(u8, path, "/n/os")) return "/"; + if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; + if (isVirtual(path)) return null; + return path; } -test "self files share the regular file limit without preallocating it" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const contents = try gpa.alloc(u8, limits.max_stream_bytes + 17); - defer gpa.free(contents); - @memset(contents, 'x'); - const pane = try p.setTestFile(contents); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); - const bytes = try read(p, path); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, contents, bytes); -} +pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[4096]u8) ?Resolved { + if (word.len == 0 or std.mem.indexOfScalar(u8, word, 0) != null) return null; + var joined_buf: [4096]u8 = undefined; + const joined = if (word[0] == '/') word else std.fmt.bufPrint(&joined_buf, "{s}/{s}", .{ cwd, word }) catch return null; + if (std.mem.eql(u8, std.mem.trimEnd(u8, joined, "/"), "/n")) return .{ .path = "/n" }; -test "bounded reads accept exact OS file lengths and empty files" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var contents: [8209]u8 = @splat('x'); - contents[contents.len - 1] = '\n'; - for ([_][]const u8{ &contents, "" }) |expected| { - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "limited.txt", .data = expected }); - var path_buf: [4096]u8 = undefined; - const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "limited.txt", &path_buf)]; - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); - for ([_][]const u8{ native, explicit }) |path| { - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, expected, bytes); - if (expected.len > 0) { - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } + if (std.mem.startsWith(u8, joined, "/n/")) { + const explicit = joined[3..]; + const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; + const name = explicit[0..cut]; + const path = if (cut < explicit.len) explicit[cut..] else "/"; + if (std.mem.eql(u8, name, "os")) { + var native_buf: [4096]u8 = undefined; + const native = resolveOs(path, &native_buf) orelse return null; + return .{ .path = std.fmt.bufPrint(out, "/n/os{s}", .{native.path}) catch return null }; + } + if (std.mem.eql(u8, name, "self")) return resolveVirtual(p, path, out); + const core = p orelse return null; + for (core.fs.mounts.items) |mount| { + if (!std.mem.eql(u8, mount.name, name)) continue; + const normalized = normalizeVirtualPath(path, out) orelse return null; + var remote_path: [4096]u8 = undefined; + const saved = std.fmt.bufPrint(&remote_path, "/n/{s}/{s}", .{ name, normalized }) catch return null; + @memcpy(out[0..saved.len], saved); + return .{ .path = out[0..saved.len] }; } + return null; } - try tmp.dir.createDir(std.testing.io, "empty", .default_dir); - var path_buf: [4096]u8 = undefined; - const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "empty", &path_buf)]; - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); - const empty = try readLimit(p, explicit, 0); - defer gpa.free(empty); - try std.testing.expectEqual(@as(usize, 0), empty.len); - // The directory's node stays in the table for the listener to collect - // once no connection names it (src/9p_io.zig, collectOs): a client may - // have walked to the same directory meanwhile and hold it by that node. - try std.testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); - try std.testing.expectEqualStrings(native, p.fs.os_paths.items[0].path); -} - -test "bounded reads apply the same limits to self bodies and embedded sources" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - var contents: [8209]u8 = @splat('x'); - contents[contents.len - 1] = '\n'; - for ([_][]const u8{ &contents, "" }) |expected| { - const pane = try p.setTestFile(expected); - for ([_][]const u8{ "/virtual", "/n/self" }) |prefix| { - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/pane/{d}/body", .{ prefix, pane.serial }); - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, expected, bytes); - if (expected.len > 0) { - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } - try std.testing.expectEqualSlices(u8, expected, pane.file.?.content); - } - } - if (limits.embedded_sources) { - const source = findEmbeddedSource("src/look.zig", false).?; - for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig" }) |path| { - const bytes = try readLimit(p, path, source.contents.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(source.contents, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, source.contents.len - 1)); - } - const bytes = try readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(source.contents, bytes); - try std.testing.expectError(error.FileTooLarge, readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len - 1)); - } -} - -test "bounded reads count rendered directory paths and unknown self lengths" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; // so listeners has a line - for ([_][]const u8{ "/n", "/virtual", "/n/self", "/virtual/pane", "/virtual/listeners", "/virtual/README" }) |path| { - const expected = try read(p, path); - defer gpa.free(expected); - try std.testing.expect(expected.len > 0); - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); + if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); + if (resolveOs(joined, out)) |found| return found; + if (resolveVirtual(p, joined, out)) |found| return found; + // `.`, `..` and `./x` name the pane's directory, never the served tree: + // with that directory gone they name nothing (`.` would be /virtual/). + if (!dotRelative(word)) if (resolveVirtual(p, word, out)) |found| return found; + if (resolveEmbedded(word, cwd, out)) |source| { + const path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null; + return .{ .path = path }; } - try std.testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); -} - -test "bounded reads release terminal snapshots after success and size refusal" { - const gpa = std.testing.allocator; - const p = try th.withTerm(gpa); - defer p.deinit(); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{th.serialOf(p)}); - const empty = try readLimit(p, path, 0); - defer gpa.free(empty); - try std.testing.expectEqual(@as(usize, 0), empty.len); - p.update(.{ .output = .{ .pane = 0, .bytes = "limited terminal output" } }); - const expected = "limited terminal output\n"; // a line ends with its newline - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - for (p.fs.opens) |o| try std.testing.expectEqual(@as(u64, 0), o.node); + return null; } -test "bounded reads probe size-unknown proc files at the exact limit" { - if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const expected = read(p, "/proc/version") catch |err| return switch (err) { - error.FileNotFound, error.PermissionDenied => error.SkipZigTest, - else => err, - }; - defer gpa.free(expected); - try std.testing.expect(expected.len > 0); - var storage: [256 * 1024]u8 = undefined; - var fixed = std.heap.FixedBufferAllocator.init(&storage); - const bounded = try readFileLimit(fixed.allocator(), "/proc/version", limits.max_stream_bytes); - try std.testing.expectEqualStrings(expected, bounded); - fixed.allocator().free(bounded); - for ([_][]const u8{ "/proc/version", "/n/os/proc/version" }) |path| { - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } +/// Whether `word` is spelled relative to the directory it is looked from: +/// `.`, `..`, `./x`, `../x`. +pub fn dotRelative(word: []const u8) bool { + const w = std.mem.trimEnd(u8, word, "/"); + return std.mem.eql(u8, w, ".") or std.mem.eql(u8, w, "..") or + std.mem.startsWith(u8, word, "./") or std.mem.startsWith(u8, word, "../"); } -test "self file reads release partial allocations when memory runs out" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const contents = try gpa.alloc(u8, 65537); - defer gpa.free(contents); - @memset(contents, 'x'); - const pane = try p.setTestFile(contents); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); - const Read = struct { - fn run(allocator: std.mem.Allocator, core: *Pardes, name: []const u8) !void { - const original = core.gpa; - core.gpa = allocator; - defer core.gpa = original; - const bytes = read(core, name) catch |err| return switch (err) { - error.WriteFailed => error.OutOfMemory, - else => err, - }; - defer allocator.free(bytes); - try std.testing.expectEqual(@as(usize, 65537), bytes.len); - } - }; - try std.testing.checkAllAllocationFailures(gpa, Read.run, .{ p, path }); - try std.testing.expectEqualSlices(u8, contents, pane.file.?.content); +/// Where a path really is on the host, and whether it is a directory. The +/// path may lie in a mount this editor serves, so the turn is given up for +/// the syscalls: another thread answers them. +/// A path's leading `~` -- alone, or before `/` or `:` (`~/x:12`) -- is the +/// home directory: $HOME, else the passwd entry's. `~user/...` is that +/// user's. As in a shell, `~` is home even beside a file named `~` in the +/// current directory. Every entry point that takes a path the user typed +/// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, +/// Restore, a forwarded `pardes ~/x`. The path itself when there is no +/// `~` to expand, or no home for it. +pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { + if (path.len == 0 or path[0] != '~') return path; + // Home as the session that recorded found it (src/tape.zig). + return pardes.tape.value(.env, expandHomeHost, .{ path, out }); } -test "oversized OS files fail before allocating their contents" { - if (!platform_has_fs) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const file = try tmp.dir.createFile(std.testing.io, "oversized", .{}); - defer file.close(std.testing.io); - try file.setLength(std.testing.io, limits.max_file_bytes + 1); - var path_buf: [4096]u8 = undefined; - const path_len = try tmp.dir.realPathFile(std.testing.io, "oversized", &path_buf); - var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); - try std.testing.expectError(error.FileTooLarge, readFile(failing.allocator(), path_buf[0..path_len])); - try std.testing.expectEqual(@as(usize, 0), failing.allocations); +fn expandHomeHost(path: []const u8, out: *[4096]u8) []const u8 { + return expandHomeFrom(path, out, std.c.getenv("HOME")); } -test "filesystem roots list their namespaces without dialing remote mounts" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try p.fs.mount(gpa, "peer", "unavailable-session"); - for ([_][]const u8{ "/n", "/n/", "/n///" }) |path| { - const contents = try read(p, path); - defer gpa.free(contents); - try std.testing.expectEqualStrings("/n/os/\n/n/self/\n/n/peer/\n", contents); - var buf: [4096]u8 = undefined; - try std.testing.expectEqualStrings("/n", resolve(p, path, "/", &buf).?.path); - try std.testing.expectError(error.IsDirectory, write(p, path, "")); - } - const bare = try read(p, "/virtual"); - defer gpa.free(bare); - const slashed = try read(p, "/virtual/"); - defer gpa.free(slashed); - try std.testing.expectEqualStrings(bare, slashed); - try std.testing.expect(std.mem.indexOf(u8, bare, "/virtual/index\n") != null); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual", "")); +/// expandHome with HOME given (null: unset), so a test need not change the +/// process's environment, which a child spawned later reads. +fn expandHomeFrom(path: []const u8, out: *[4096]u8, env_home: ?[*:0]const u8) []const u8 { + if (path.len == 0 or path[0] != '~') return path; + const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; + const home = (if (end == 1) homeDir(env_home) else userHome(path[1..end])) orelse return path; + const trimmed = std.mem.trimEnd(u8, home, "/"); + const rest = path[end..]; + if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; + return std.fmt.bufPrint(out, "{s}{s}", .{ trimmed, rest }) catch path; } -test "virtual body writes can read their input from the same pane" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("same pane contents\n"); - const event_node = tree.Node.of(pane.serial, .event); - _ = tree.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); - defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = event_node }); - var path_buffer: [64]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buffer, "/virtual/pane/{d}/body", .{pane.serial}); - try write(p, path, pane.file.?.content); - try std.testing.expectEqualStrings("same pane contents\n", pane.file.?.content); - // The truncation and the write are one undo step. - try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); - const events = &p.panes[p.view().active].?.fs.events; - try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "ED")); - events.pop(); - try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "EI")); - events.pop(); - try std.testing.expect(events.empty()); - try write(p, path, pane.file.?.content[5..]); - try std.testing.expectEqualStrings("pane contents\n", pane.file.?.content); +fn homeDir(env_home: ?[*:0]const u8) ?[]const u8 { + if (env_home) |h| if (h[0] != 0) return std.mem.span(h); + const pw = std.c.getpwuid(std.c.getuid()) orelse return null; + return std.mem.span(pw.dir orelse return null); } -pub fn isVirtual(path: []const u8) bool { - return std.mem.eql(u8, path, "/virtual") or std.mem.startsWith(u8, path, "/virtual/") or - std.mem.eql(u8, path, "/n") or std.mem.startsWith(u8, path, "/n/"); +fn userHome(name: []const u8) ?[]const u8 { + var z: [256]u8 = undefined; + const name_z = std.fmt.bufPrintSentinel(&z, "{s}", .{name}, 0) catch return null; + const pw = std.c.getpwnam(name_z) orelse return null; + return std.mem.span(pw.dir orelse return null); } -/// std's `statFile`, but a name with a part over 255 bytes is NameTooLong: -/// std's own takes the kernel's ENAMETOOLONG for that for a bug and panics -/// (Io.Threaded dirStatFileLinux), and such a name comes from anyone who -/// writes one to `name`, `look` or DumpDir. -pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOptions) !std.Io.File.Stat { - var parts = std.mem.tokenizeScalar(u8, path, '/'); - while (parts.next()) |part| if (part.len > 255) return error.NameTooLong; - return std.Io.Dir.cwd().statFile(io, path, options); +pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { + if (comptime !platform_has_fs) return null; + var z: [4096]u8 = undefined; + const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; + return pardes.tape.site(.resolve, null, resolveHost, .{ path_z, out }); } -test "a path with a part over 255 bytes is NameTooLong, never a panic" { - const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; - try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); +fn resolveHost(path_z: [:0]const u8, out: *[4096]u8) ?Resolved { + const resolved = realpath(path_z, out) orelse return null; + return .{ .path = std.mem.span(resolved), .dir = isDir(resolved) }; } -/// Make `dir` and each directory above it that is missing, as `mkdir -p` -/// does: one already there is no failure. A failure shows at the open -/// that follows. -pub fn makeDirs(dir: []const u8) void { - if (comptime !platform_has_fs) return; - if (dir.len == 0) return; - pardes.tape.site(.make_dirs, null, makeDirsHost, .{dir}); +fn resolveVirtual(p: ?*pardes.Pardes, path: []const u8, out: *[4096]u8) ?Resolved { + var normalized_buf: [4096]u8 = undefined; + const normalized = normalizeVirtualPath(path, &normalized_buf) orelse return null; + if (p) |core| if (tree.resolveSelf(core, normalized) != null) + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; + if (findEmbeddedSource(normalized, false)) |source| + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null }; + if (sources_fs.node(normalized) != null) + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; + return null; } -fn makeDirsHost(dir: []const u8) void { - _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; -} - -/// Whether `dir` is not there to make because one above it refuses: its -/// nearest ancestor that is there may not be searched or written (EACCES: -/// `noperm/a/b`, `/proc/1/root/x`). -pub fn deniedAbove(dir: []const u8) bool { - if (comptime !platform_has_fs) return false; - var at: ?[]const u8 = dir; - while (at) |d| : (at = std.Io.Dir.path.dirname(d)) { - var z: [4096]u8 = undefined; - const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{d}, 0) catch return false; - if (libc.access(dz.ptr, 0) != 0) continue; // F_OK - return libc.access(dz.ptr, 2 | 1) != 0; // W_OK | X_OK - } - return false; -} - -test "a directory under one that may not be searched or written is denied, one merely missing is not" { - // The refusing directory is Linux's /proc/1/root. - if (comptime @import("builtin").os.tag == .linux) try std.testing.expect(deniedAbove("/proc/1/root/x/y")); - try std.testing.expect(!deniedAbove("/tmp/pardes-surely-missing-dir/a/b")); -} - -pub fn localPath(path: []const u8) ?[]const u8 { - if (std.mem.eql(u8, path, "/n/os")) return "/"; - if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; - if (isVirtual(path)) return null; - return path; -} - -test "explicit OS paths retain their namespace until an OS boundary" { - for ([_]struct { declared: []const u8, native: ?[]const u8 }{ - .{ .declared = "/n/os", .native = "/" }, - .{ .declared = "/n/os/project/file", .native = "/project/file" }, - .{ .declared = "/n/os/virtual/index", .native = "/virtual/index" }, - .{ .declared = "/n/os/n/self/index", .native = "/n/self/index" }, - .{ .declared = "/n/self/index", .native = null }, - .{ .declared = "/n/peer/os/project/file", .native = null }, - .{ .declared = "/virtual/index", .native = null }, - .{ .declared = "/project/file", .native = "/project/file" }, - }) |case| { - const native = localPath(case.declared); - if (case.native) |expected| try std.testing.expectEqualStrings(expected, native.?) else try std.testing.expect(native == null); - } -} - -pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[4096]u8) ?Resolved { - if (word.len == 0 or std.mem.indexOfScalar(u8, word, 0) != null) return null; - var joined_buf: [4096]u8 = undefined; - const joined = if (word[0] == '/') word else std.fmt.bufPrint(&joined_buf, "{s}/{s}", .{ cwd, word }) catch return null; - if (std.mem.eql(u8, std.mem.trimEnd(u8, joined, "/"), "/n")) return .{ .path = "/n" }; - - if (std.mem.startsWith(u8, joined, "/n/")) { - const explicit = joined[3..]; - const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; - const name = explicit[0..cut]; - const path = if (cut < explicit.len) explicit[cut..] else "/"; - if (std.mem.eql(u8, name, "os")) { - var native_buf: [4096]u8 = undefined; - const native = resolveOs(path, &native_buf) orelse return null; - return .{ .path = std.fmt.bufPrint(out, "/n/os{s}", .{native.path}) catch return null }; - } - if (std.mem.eql(u8, name, "self")) return resolveVirtual(p, path, out); - const core = p orelse return null; - for (core.fs.mounts.items) |mount| { - if (!std.mem.eql(u8, mount.name, name)) continue; - const normalized = normalizeVirtualPath(path, out) orelse return null; - var remote_path: [4096]u8 = undefined; - const saved = std.fmt.bufPrint(&remote_path, "/n/{s}/{s}", .{ name, normalized }) catch return null; - @memcpy(out[0..saved.len], saved); - return .{ .path = out[0..saved.len] }; - } - return null; - } - if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); - if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); - if (resolveOs(joined, out)) |found| return found; - if (resolveVirtual(p, joined, out)) |found| return found; - // `.`, `..` and `./x` name the pane's directory, never the served tree: - // with that directory gone they name nothing (`.` would be /virtual/). - if (!dotRelative(word)) if (resolveVirtual(p, word, out)) |found| return found; - if (resolveEmbedded(word, cwd, out)) |source| { - const path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null; - return .{ .path = path }; - } - return null; -} - -/// Whether `word` is spelled relative to the directory it is looked from: -/// `.`, `..`, `./x`, `../x`. -pub fn dotRelative(word: []const u8) bool { - const w = std.mem.trimEnd(u8, word, "/"); - return std.mem.eql(u8, w, ".") or std.mem.eql(u8, w, "..") or - std.mem.startsWith(u8, word, "./") or std.mem.startsWith(u8, word, "../"); -} - -/// Where a path really is on the host, and whether it is a directory. The -/// path may lie in a mount this editor serves, so the turn is given up for -/// the syscalls: another thread answers them. -/// A path's leading `~` -- alone, or before `/` or `:` (`~/x:12`) -- is the -/// home directory: $HOME, else the passwd entry's. `~user/...` is that -/// user's. As in a shell, `~` is home even beside a file named `~` in the -/// current directory. Every entry point that takes a path the user typed -/// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, -/// Restore, a forwarded `pardes ~/x`. The path itself when there is no -/// `~` to expand, or no home for it. -pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { - if (path.len == 0 or path[0] != '~') return path; - // Home as the session that recorded found it (src/tape.zig). - return pardes.tape.value(.env, expandHomeHost, .{ path, out }); -} - -fn expandHomeHost(path: []const u8, out: *[4096]u8) []const u8 { - return expandHomeFrom(path, out, std.c.getenv("HOME")); -} - -/// expandHome with HOME given (null: unset), so a test need not change the -/// process's environment, which a child spawned later reads. -fn expandHomeFrom(path: []const u8, out: *[4096]u8, env_home: ?[*:0]const u8) []const u8 { - if (path.len == 0 or path[0] != '~') return path; - const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; - const home = (if (end == 1) homeDir(env_home) else userHome(path[1..end])) orelse return path; - const trimmed = std.mem.trimEnd(u8, home, "/"); - const rest = path[end..]; - if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; - return std.fmt.bufPrint(out, "{s}{s}", .{ trimmed, rest }) catch path; -} - -fn homeDir(env_home: ?[*:0]const u8) ?[]const u8 { - if (env_home) |h| if (h[0] != 0) return std.mem.span(h); - const pw = std.c.getpwuid(std.c.getuid()) orelse return null; - return std.mem.span(pw.dir orelse return null); -} - -fn userHome(name: []const u8) ?[]const u8 { - var z: [256]u8 = undefined; - const name_z = std.fmt.bufPrintSentinel(&z, "{s}", .{name}, 0) catch return null; - const pw = std.c.getpwnam(name_z) orelse return null; - return std.mem.span(pw.dir orelse return null); -} - -test "a leading ~ is home, from HOME or else the passwd entry" { - var out: [4096]u8 = undefined; - const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; - var want: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); - try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); - try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); - try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); - try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); - - // HOME unset: the passwd entry's home. - const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; - var from_passwd: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, null)); -} - -pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { - if (comptime !platform_has_fs) return null; - var z: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; - return pardes.tape.site(.resolve, null, resolveHost, .{ path_z, out }); -} - -fn resolveHost(path_z: [:0]const u8, out: *[4096]u8) ?Resolved { - const resolved = realpath(path_z, out) orelse return null; - return .{ .path = std.mem.span(resolved), .dir = isDir(resolved) }; -} - -fn resolveVirtual(p: ?*pardes.Pardes, path: []const u8, out: *[4096]u8) ?Resolved { - var normalized_buf: [4096]u8 = undefined; - const normalized = normalizeVirtualPath(path, &normalized_buf) orelse return null; - if (p) |core| if (tree.resolveSelf(core, normalized) != null) - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; - if (findEmbeddedSource(normalized, false)) |source| - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null }; - if (sources_fs.node(normalized) != null) - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; - return null; -} - -pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { - return readLimit(p, path, limits.max_file_bytes); +pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { + return readLimit(p, path, limits.max_file_bytes); } pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { @@ -1135,40 +708,6 @@ pub fn restorePath(typed: []const u8, dir_setting: []const u8, out: *[4096]u8) [ return out[0..n]; } -test "Restore prefers default directory then falls back to original path" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const relative = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/a.dump", .{tmp.sub_path}); - defer gpa.free(relative); - const base = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/dumps", .{tmp.sub_path}); - defer gpa.free(base); - const nested = try std.fmt.allocPrint(gpa, "dumps/.zig-cache/tmp/{s}", .{tmp.sub_path}); - defer gpa.free(nested); - try tmp.dir.createDirPath(std.testing.io, nested); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "dumps/a.dump", .data = "short name" }); - const short = try readRestore(gpa, "a.dump", base); - defer gpa.free(short); - try std.testing.expectEqualStrings("short name", short); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.dump", .data = "original" }); - const fallback = try readRestore(gpa, relative, base); - defer gpa.free(fallback); - try std.testing.expectEqualStrings("original", fallback); - const candidate = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, relative }); - defer gpa.free(candidate); - try writeFile(candidate, "default"); - const preferred = try readRestore(gpa, relative, base); - defer gpa.free(preferred); - try std.testing.expectEqualStrings("default", preferred); - const absolute = try tmp.dir.realPathFileAlloc(std.testing.io, "a.dump", gpa); - defer gpa.free(absolute); - const direct = try readRestore(gpa, absolute, base); - defer gpa.free(direct); - try std.testing.expectEqualStrings("original", direct); - try std.testing.expectError(error.FileNotFound, readRestore(gpa, "missing-restore-test.dump", base)); -} - fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) { @@ -1484,6 +1023,467 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { return error.NotMounted; } +test "/os refuses a rename or a mode change as not permitted, in words, and still truncates to zero" { + const p = try th.withFile(std.testing.allocator, "x\n"); + defer p.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "kept.txt", .data = "kept\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var node: u64 = os_root; + var parts = std.mem.tokenizeScalar(u8, dir, '/'); + while (parts.next()) |part| node = th.look_up(p, node, part).reply.attr.node; + node = th.look_up(p, node, "kept.txt").reply.attr.node; + for ([_]Req{ + .{ .tag = 1, .op = .setattr, .node = node, .set = .{ .mode = true } }, + .{ .tag = 2, .op = .setattr, .node = node, .set = .{ .name = true }, .data = "moved.txt" }, + }) |req| { + const r = th.call(p, req); + try std.testing.expectEqual(E.PERM, r.errno()); + try std.testing.expectStringStartsWith(r.reply.ename, "permission denied"); + } + try std.testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 3, .op = .setattr, .node = node, .truncate = true }).reply.status); +} + +test "mounts own their names and dials and reject duplicate or reserved names" { + const gpa = std.testing.allocator; + var ns: Namespace = .{}; + defer ns.deinit(gpa); + var name = "peer".*; + var dial = "/tmp/peer.sock".*; + try ns.mount(gpa, &name, &dial); + @memset(&name, 'x'); + @memset(&dial, 'x'); + try std.testing.expectEqualStrings("peer", ns.mounts.items[0].name); + try std.testing.expectEqualStrings("/tmp/peer.sock", ns.mounts.items[0].dial); + try std.testing.expectError(error.AlreadyMounted, ns.mount(gpa, "peer", "/tmp/other.sock")); + for ([_][]const u8{ "", ".", "..", "os", "self", "a/b", "with space" }) |bad| + try std.testing.expectError(error.BadMountName, ns.mount(gpa, bad, "/tmp/peer.sock")); + for ([_][]const u8{ "", "a\x00b", "tcp!127.0.0.1!0", "tcp!localhost!564" }) |bad| + try std.testing.expectError(error.BadDial, ns.mount(gpa, "valid", bad)); + for (1..max_mounts) |i| { + var buf: [16]u8 = undefined; + try ns.mount(gpa, try std.fmt.bufPrint(&buf, "peer{d}", .{i}), "/tmp/peer.sock"); + } + try std.testing.expectEqual(max_mounts, ns.mounts.items.len); + try std.testing.expectError(error.TooManyMounts, ns.mount(gpa, "full", "/tmp/peer.sock")); +} + +test "mount allocation failures preserve prior mounts and release partial copies" { + const Check = struct { + fn run(gpa: std.mem.Allocator) !void { + var ns: Namespace = .{}; + defer ns.deinit(gpa); + try ns.mount(gpa, "first", "/tmp/first.sock"); + ns.mount(gpa, "second", "/tmp/second.sock") catch |err| { + try std.testing.expectEqual(@as(usize, 1), ns.mounts.items.len); + try std.testing.expectEqualStrings("first", ns.mounts.items[0].name); + try std.testing.expectEqualStrings("/tmp/first.sock", ns.mounts.items[0].dial); + return err; + }; + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{}); +} + +test "unmount refuses pane paths inherited directories and queued save targets" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try p.fs.mount(gpa, "peer", "/tmp/peer.sock"); + const pane = try p.setTestFile("unsaved\n"); + for ([_][]const u8{ "/n/peer", "/n/peer/file", "/n/peer/dir/file" }) |path| { + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, path); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + } + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); + const slot = p.freeSlot().?; + const shell = try p.newShell(slot, "/n/peer/dir"); + p.setCwd(slot, "/n/peer/dir"); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + pane.cwd = .{ .inherited = shell }; + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + p.setCwd(slot, "/"); + while (p.nextEffect()) |_| {} + p.emit(.{ .save_text = .{ .pane = 0, .serial = pane.serial, .path = .from("/n/peer/pending") } }); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + while (p.nextEffect()) |_| {} + try unmount(p, "peer"); + try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); + try std.testing.expectError(error.NotMounted, unmount(p, "peer")); + try p.fs.mount(gpa, "peer", "/tmp/other.sock"); + try std.testing.expectEqualStrings("/tmp/other.sock", p.fs.mounts.items[0].dial); +} + +test "virtual writes enforce permissions even when contents are empty" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + for ([_][]const u8{ "", "bytes" }) |bytes| { + for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README" }) |path| + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); + // /log takes one word, `follow`, and only on the open it changes. + if (bytes.len > 0) if (write(p, "/n/self/log", bytes)) |_| return error.TestUnexpectedResult else |_| {}; + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/pane", bytes)); + try std.testing.expectError(error.FileNotFound, write(p, "/virtual/missing", bytes)); + try std.testing.expectError(error.FileNotFound, write(p, "/virtual/cons", bytes)); + if (limits.embedded_sources) { + for ([_][]const u8{ "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); + } else try std.testing.expectError(error.FileNotFound, write(p, "/virtual/src/fs.zig", bytes)); + } + for (p.fs.opens) |o| try std.testing.expect(o.node == 0); +} + +test "direct self reads and writes use the same dot paths as Look" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("old contents\n"); + var path_buf: [256]u8 = undefined; + for ([_][]const u8{ "/virtual", "/n/self" }) |root| { + const path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/{d}/../{d}/body/./", .{ root, pane.serial, pane.serial }); + try write(p, path, "replacement\n"); + try std.testing.expectEqualStrings("replacement\n", pane.file.?.content); + const bytes = try read(p, path); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(pane.file.?.content, bytes); + var resolved: [4096]u8 = undefined; + const canonical = resolve(p, path, "/", &resolved).?; + try std.testing.expectEqual(tree.resolveSelf(p, canonical.path[9..]), tree.resolveSelf(p, path[root.len..])); + try std.testing.expectEqual(@as(?u64, tree.root), tree.resolveSelf(p, "./pane/../../")); + const index_path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/../index", .{root}); + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, index_path, "")); + const index = try read(p, index_path); + defer gpa.free(index); + try std.testing.expect(std.mem.indexOf(u8, index, "/test.txt") != null); + } + var overlong: [4110]u8 = @splat('x'); + @memcpy(overlong[0..9], "/virtual/"); + var resolved: [4096]u8 = undefined; + try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); + try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); + try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); +} + +test "self files share the regular file limit without preallocating it" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const contents = try gpa.alloc(u8, limits.max_stream_bytes + 17); + defer gpa.free(contents); + @memset(contents, 'x'); + const pane = try p.setTestFile(contents); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); + const bytes = try read(p, path); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, contents, bytes); +} + +test "bounded reads accept exact OS file lengths and empty files" { + if (!platform_has_fs) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var contents: [8209]u8 = @splat('x'); + contents[contents.len - 1] = '\n'; + for ([_][]const u8{ &contents, "" }) |expected| { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "limited.txt", .data = expected }); + var path_buf: [4096]u8 = undefined; + const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "limited.txt", &path_buf)]; + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); + for ([_][]const u8{ native, explicit }) |path| { + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, expected, bytes); + if (expected.len > 0) { + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + } + } + try tmp.dir.createDir(std.testing.io, "empty", .default_dir); + var path_buf: [4096]u8 = undefined; + const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "empty", &path_buf)]; + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); + const empty = try readLimit(p, explicit, 0); + defer gpa.free(empty); + try std.testing.expectEqual(@as(usize, 0), empty.len); + // The directory's node stays in the table for the listener to collect + // once no connection names it (src/9p_io.zig, collectOs): a client may + // have walked to the same directory meanwhile and hold it by that node. + try std.testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); + try std.testing.expectEqualStrings(native, p.fs.os_paths.items[0].path); +} + +test "bounded reads apply the same limits to self bodies and embedded sources" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + var contents: [8209]u8 = @splat('x'); + contents[contents.len - 1] = '\n'; + for ([_][]const u8{ &contents, "" }) |expected| { + const pane = try p.setTestFile(expected); + for ([_][]const u8{ "/virtual", "/n/self" }) |prefix| { + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/pane/{d}/body", .{ prefix, pane.serial }); + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, expected, bytes); + if (expected.len > 0) { + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + try std.testing.expectEqualSlices(u8, expected, pane.file.?.content); + } + } + if (limits.embedded_sources) { + const source = findEmbeddedSource("src/look.zig", false).?; + for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig" }) |path| { + const bytes = try readLimit(p, path, source.contents.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(source.contents, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, source.contents.len - 1)); + } + const bytes = try readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(source.contents, bytes); + try std.testing.expectError(error.FileTooLarge, readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len - 1)); + } +} + +test "bounded reads count rendered directory paths and unknown self lengths" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; // so listeners has a line + for ([_][]const u8{ "/n", "/virtual", "/n/self", "/virtual/pane", "/virtual/listeners", "/virtual/README" }) |path| { + const expected = try read(p, path); + defer gpa.free(expected); + try std.testing.expect(expected.len > 0); + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + try std.testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); +} + +test "bounded reads release terminal snapshots after success and size refusal" { + const gpa = std.testing.allocator; + const p = try th.withTerm(gpa); + defer p.deinit(); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{th.serialOf(p)}); + const empty = try readLimit(p, path, 0); + defer gpa.free(empty); + try std.testing.expectEqual(@as(usize, 0), empty.len); + p.update(.{ .output = .{ .pane = 0, .bytes = "limited terminal output" } }); + const expected = "limited terminal output\n"; // a line ends with its newline + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + for (p.fs.opens) |o| try std.testing.expectEqual(@as(u64, 0), o.node); +} + +test "bounded reads probe size-unknown proc files at the exact limit" { + if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const expected = read(p, "/proc/version") catch |err| return switch (err) { + error.FileNotFound, error.PermissionDenied => error.SkipZigTest, + else => err, + }; + defer gpa.free(expected); + try std.testing.expect(expected.len > 0); + var storage: [256 * 1024]u8 = undefined; + var fixed = std.heap.FixedBufferAllocator.init(&storage); + const bounded = try readFileLimit(fixed.allocator(), "/proc/version", limits.max_stream_bytes); + try std.testing.expectEqualStrings(expected, bounded); + fixed.allocator().free(bounded); + for ([_][]const u8{ "/proc/version", "/n/os/proc/version" }) |path| { + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } +} + +test "self file reads release partial allocations when memory runs out" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const contents = try gpa.alloc(u8, 65537); + defer gpa.free(contents); + @memset(contents, 'x'); + const pane = try p.setTestFile(contents); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); + const Read = struct { + fn run(allocator: std.mem.Allocator, core: *Pardes, name: []const u8) !void { + const original = core.gpa; + core.gpa = allocator; + defer core.gpa = original; + const bytes = read(core, name) catch |err| return switch (err) { + error.WriteFailed => error.OutOfMemory, + else => err, + }; + defer allocator.free(bytes); + try std.testing.expectEqual(@as(usize, 65537), bytes.len); + } + }; + try std.testing.checkAllAllocationFailures(gpa, Read.run, .{ p, path }); + try std.testing.expectEqualSlices(u8, contents, pane.file.?.content); +} + +test "oversized OS files fail before allocating their contents" { + if (!platform_has_fs) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const file = try tmp.dir.createFile(std.testing.io, "oversized", .{}); + defer file.close(std.testing.io); + try file.setLength(std.testing.io, limits.max_file_bytes + 1); + var path_buf: [4096]u8 = undefined; + const path_len = try tmp.dir.realPathFile(std.testing.io, "oversized", &path_buf); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + try std.testing.expectError(error.FileTooLarge, readFile(failing.allocator(), path_buf[0..path_len])); + try std.testing.expectEqual(@as(usize, 0), failing.allocations); +} + +test "filesystem roots list their namespaces without dialing remote mounts" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try p.fs.mount(gpa, "peer", "unavailable-session"); + for ([_][]const u8{ "/n", "/n/", "/n///" }) |path| { + const contents = try read(p, path); + defer gpa.free(contents); + try std.testing.expectEqualStrings("/n/os/\n/n/self/\n/n/peer/\n", contents); + var buf: [4096]u8 = undefined; + try std.testing.expectEqualStrings("/n", resolve(p, path, "/", &buf).?.path); + try std.testing.expectError(error.IsDirectory, write(p, path, "")); + } + const bare = try read(p, "/virtual"); + defer gpa.free(bare); + const slashed = try read(p, "/virtual/"); + defer gpa.free(slashed); + try std.testing.expectEqualStrings(bare, slashed); + try std.testing.expect(std.mem.indexOf(u8, bare, "/virtual/index\n") != null); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual", "")); +} + +test "virtual body writes can read their input from the same pane" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("same pane contents\n"); + const event_node = tree.Node.of(pane.serial, .event); + _ = tree.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = event_node }); + var path_buffer: [64]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buffer, "/virtual/pane/{d}/body", .{pane.serial}); + try write(p, path, pane.file.?.content); + try std.testing.expectEqualStrings("same pane contents\n", pane.file.?.content); + // The truncation and the write are one undo step. + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); + const events = &p.panes[p.view().active].?.fs.events; + try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "ED")); + events.pop(); + try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "EI")); + events.pop(); + try std.testing.expect(events.empty()); + try write(p, path, pane.file.?.content[5..]); + try std.testing.expectEqualStrings("pane contents\n", pane.file.?.content); +} + +test "a path with a part over 255 bytes is NameTooLong, never a panic" { + const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; + try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); +} + +test "a directory under one that may not be searched or written is denied, one merely missing is not" { + // The refusing directory is Linux's /proc/1/root. + if (comptime @import("builtin").os.tag == .linux) try std.testing.expect(deniedAbove("/proc/1/root/x/y")); + try std.testing.expect(!deniedAbove("/tmp/pardes-surely-missing-dir/a/b")); +} + +test "explicit OS paths retain their namespace until an OS boundary" { + for ([_]struct { declared: []const u8, native: ?[]const u8 }{ + .{ .declared = "/n/os", .native = "/" }, + .{ .declared = "/n/os/project/file", .native = "/project/file" }, + .{ .declared = "/n/os/virtual/index", .native = "/virtual/index" }, + .{ .declared = "/n/os/n/self/index", .native = "/n/self/index" }, + .{ .declared = "/n/self/index", .native = null }, + .{ .declared = "/n/peer/os/project/file", .native = null }, + .{ .declared = "/virtual/index", .native = null }, + .{ .declared = "/project/file", .native = "/project/file" }, + }) |case| { + const native = localPath(case.declared); + if (case.native) |expected| try std.testing.expectEqualStrings(expected, native.?) else try std.testing.expect(native == null); + } +} + +test "a leading ~ is home, from HOME or else the passwd entry" { + var out: [4096]u8 = undefined; + const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; + var want: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); + try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); + try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); + try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); + + // HOME unset: the passwd entry's home. + const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; + var from_passwd: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, null)); +} + +test "Restore prefers default directory then falls back to original path" { + if (!platform_has_fs) return error.SkipZigTest; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const relative = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/a.dump", .{tmp.sub_path}); + defer gpa.free(relative); + const base = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/dumps", .{tmp.sub_path}); + defer gpa.free(base); + const nested = try std.fmt.allocPrint(gpa, "dumps/.zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(nested); + try tmp.dir.createDirPath(std.testing.io, nested); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "dumps/a.dump", .data = "short name" }); + const short = try readRestore(gpa, "a.dump", base); + defer gpa.free(short); + try std.testing.expectEqualStrings("short name", short); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.dump", .data = "original" }); + const fallback = try readRestore(gpa, relative, base); + defer gpa.free(fallback); + try std.testing.expectEqualStrings("original", fallback); + const candidate = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, relative }); + defer gpa.free(candidate); + try writeFile(candidate, "default"); + const preferred = try readRestore(gpa, relative, base); + defer gpa.free(preferred); + try std.testing.expectEqualStrings("default", preferred); + const absolute = try tmp.dir.realPathFileAlloc(std.testing.io, "a.dump", gpa); + defer gpa.free(absolute); + const direct = try readRestore(gpa, absolute, base); + defer gpa.free(direct); + try std.testing.expectEqualStrings("original", direct); + try std.testing.expectError(error.FileNotFound, readRestore(gpa, "missing-restore-test.dump", base)); +} + test { _ = tree; } 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(.{}); diff --git a/src/host_io.zig b/src/host_io.zig index 9e0292b3..be741020 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1091,10 +1091,6 @@ pub const Lsp = struct { } }; -test { - _ = Lsp; -} - pub const Shell = struct { const X_OK: c_int = 1; @@ -1834,30 +1830,6 @@ pub fn resetChildSignals() void { posix.sigprocmask(posix.SIG.SETMASK, &none, null); } -test "a child starts with every signal at its default and none blocked" { - var blocked = posix.sigemptyset(); - posix.sigaddset(&blocked, posix.SIG.WINCH); - posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); - defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); - const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; - var was: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, &ignore, &was); - defer posix.sigaction(posix.SIG.HUP, &was, null); - const pid = libc.fork(); - if (pid == 0) { - resetChildSignals(); - var now: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, null, &now); - var mask = posix.sigemptyset(); - posix.sigprocmask(posix.SIG.BLOCK, null, &mask); - const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); - libc._exit(if (ok) 0 else 1); - } - var status: c_int = 0; - _ = libc.waitpid(pid, &status, 0); - try std.testing.expectEqual(@as(c_int, 0), status); -} - extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; @@ -2024,91 +1996,6 @@ pub const ChildEnv = struct { } }; -test "the pager's path is quoted only when it needs it" { - var buf: [64]u8 = undefined; - try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); - try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); - try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); -} - -test "the child environment replaces the launcher's terminal identity exactly once" { - const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - if (t.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..t.len], t); - saved_buf[t.len] = 0; - break :blk saved_buf[0..t.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - - // A launcher TERM must be shadowed rather than duplicated, and the rest of - // the environment must arrive untouched. - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); - defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); - - var slots: ChildEnv.Slots = undefined; - // Where the user named no pager: a terminal's shell pages into a - // +Pager pane (`pardes -`); a command pane's through cat. A pager the - // user named is kept. - var shell_slots: ChildEnv.Slots = undefined; - const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; - var said: usize = 0; - var systemd: usize = 0; - var j: usize = 0; - while (shell_envp[j]) |entry| : (j += 1) { - const line = std.mem.span(entry); - if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; - if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; - if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { - try std.testing.expect(std.mem.endsWith(u8, line, " -")); - said += 1; - } - } - if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); - // systemd's pager and its secure mode off, with ours only. - if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) - try std.testing.expectEqual(@as(usize, 2), systemd); - const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; - var terms: usize = 0; - var colorterms: usize = 0; - var probes: usize = 0; - var dumb = false; - var pagers: usize = 0; - var git_pagers: usize = 0; - var pager_cat = false; - var git_pager_cat = false; - var i: usize = 0; - while (envp[i]) |entry| : (i += 1) { - const line = std.mem.span(entry); - if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; - if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; - if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; - if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; - if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; - if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; - if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; - if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; - } - // A pager only where the user named none: cat, so nothing waits in less. - try std.testing.expectEqual(@as(usize, 1), pagers); - try std.testing.expectEqual(@as(usize, 1), git_pagers); - if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); - if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); - try std.testing.expectEqual(@as(usize, 1), terms); - try std.testing.expectEqual(@as(usize, 1), colorterms); - try std.testing.expectEqual(@as(usize, 1), probes); - try std.testing.expect(!dumb); - // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it - // is a separate entry and never a second TERM. - try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); -} - extern "c" fn unsetenv(name: [*:0]const u8) c_int; /// For tests: unset `name` without compacting the environment block std @@ -2280,88 +2167,6 @@ pub fn forkShell( return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; } -test "shell spawn rejects invalid directories before creating a child" { - const rcs: Shell.PromptFiles = .{}; - try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); - const too_long = @as([4096]u8, @splat('x')); - try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); - - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; - var path_buf: [4096]u8 = undefined; - const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); - const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); - const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); - try std.testing.expect(missing.len > 256); - try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); -} - -test "a forked shell is told which terminal it is talking to" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - // Whatever launched the test is the wrong answer, so make it a loud one. - const saved = libc.getenv("TERM"); - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - const span = std.mem.span(t); - if (span.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..span.len], span); - saved_buf[span.len] = 0; - break :blk saved_buf[0..span.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - _ = Shell.setenv("TERM", "dumb", 1); - - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - // The echoed command carries the unexpanded `$TERM`, so only the shell's - // own expansion can match this. - try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); - try std.testing.expect(sh.waitText( - "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, - 5_000, - )); -} - -test "shell spawn uses an explicit OS directory longer than 256 bytes" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(std.testing.io, sub_path); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; - try std.testing.expect(directory.len > 256); - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); - var expected_buf: [4096]u8 = undefined; - const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); - try std.testing.expect(sh.waitText(expected, 5_000)); -} - pub fn writeFd(fd: c_int, data: []const u8) bool { var off: usize = 0; while (off < data.len) { @@ -2485,109 +2290,7 @@ fn realShell(shell_exe: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[]cons return std.mem.span(@as([*:0]const u8, @ptrCast(r))); } -test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "start/a/b"); - var path_buf: [4096]u8 = undefined; - const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; - var inner_buf: [4096]u8 = undefined; - const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; - const rcs: Shell.PromptFiles = .{}; - var result: [4096]u8 = undefined; - // A wrapper exec'd over the shell (timeout standing in for 9ns) runs - // another, two directories down, in the foreground. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); - try std.testing.expect(sh.waitText("pardes-in-", 5_000)); - // printf runs before the inner shell takes the foreground. - var tries: usize = 0; - while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) - try std.testing.io.sleep(.fromMilliseconds(20), .awake); - try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } - // A job of the shell's own, gone into a/b, leaves the pane where the - // shell is. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); - try std.testing.expect(sh.waitText("pardes-job", 5_000)); - try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } -} - -test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(io, nested); - var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; - try std.testing.expect(directory.len > 1024); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); -} - -test "a shell whose directory was removed is not named `... (deleted)`" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "gone"); - var path_buf: [4096]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [4096]u8 = undefined; - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try tmp.dir.deleteDir(io, "gone"); - try std.testing.expect(shellCwd(child.pid, &result) == null); -} - -extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; +extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; const occ_max_depth: u8 = 8; const occ_max_visited: usize = 32; @@ -3135,46 +2838,6 @@ fn parseChildren(text: []const u8, out: []libc.pid_t) usize { return total; } -test "the children blob parses to pids, and a garbage token never becomes one" { - var out: [8]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); - try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); - try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); - try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); - try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); - var two: [2]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); -} - -test "the process group comes off the last ')', not a comm-shifted stat field" { - const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ - "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; - try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); - try std.testing.expect(parseGroupSession("") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); - try std.testing.expect(parseGroupSession("no parens here at all") == null); -} - -test "the zombie state comes off its own status line" { - try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); - try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); - try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nSta")); - try std.testing.expect(!parseZombie("State:\t")); -} - const test_shell = "/bin/bash"; const test_prompt = "PZX> "; @@ -3323,98 +2986,512 @@ fn sleepMs(ms: i64) void { std.testing.io.sleep(.fromMilliseconds(ms), .awake) catch {}; } -test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - try std.testing.expect(sh.holdsTaken(false, 200)); +// ---- what every host's vtable does alike ---- - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); +/// A Save's write: the file written through the core's filesystem, the +/// pane's watch told the new text is the editor's own (so it is no outside +/// change), and "saved" said on the pane. +pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { + filesystem.write(core, path, bytes) catch |err| + return core.saveFailed(pane, path, err); + if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { + if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { + .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, + .kind => {}, + }; + }; + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); + // The init file, saved here (Config): its settings take effect now. + pardes.exec.reapplyInitFile(core, path, bytes); +} - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); +/// A Dump's write: into the state file under a label of its own +/// (Db.putDump), or as a file of its own where `Dump export` names one or +/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its +/// goldens). +pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { + const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; + if (to) |path| { + filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); + return core.setLastDump(path); + } + var stamp: [64]u8 = undefined; + var buf: [128]u8 = undefined; + const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { + var path: [4200]u8 = undefined; + // In the words a host reports failures in (tape.Failure). + const said: pardes.tape.Failure = switch (err) { + error.NoStateFile => error.NoDumpDirectory, + error.OutOfMemory => error.OutOfMemory, + error.NoSpaceLeft => error.NoSpaceLeft, + error.AccessDenied => error.AccessDenied, + else => error.InputOutput, + }; + return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); + }; + core.setLastDump(label); } -test "Kill stops the foreground job, never the shell, and finds none with job control off" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); +/// DumpThemes: the built-in themes written below the config directory. +pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { + const config_dir = core.opts.config_dir orelse return; + const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { + core.reportError(pane, "dump themes", err); + return; + }; + defer gpa.free(out_dir); + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); +} - // At the prompt the shell is the foreground: there is nothing to stop. - try std.testing.expect(!killJob(sh.pid, sh.master)); - sleepMs(100); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +pub const PtyTests = struct { + pub fn waitBlocked(queue: *Inbox) !void { + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + queue.lock(); + const waiting = queue.waiting; + queue.unlock(); + if (waiting != 0) return; + try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + return error.ReaderDidNotBlock; + } - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.forget(); - try std.testing.expect(killJob(sh.pid, sh.master)); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + fn tail(queue: *Inbox, bytes: []u8) void { + if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + } +}; - // Job control off: the job runs in the shell's own group. - sh.forget(); - sh.send("set +m; sleep 30\n"); - sleepMs(300); - try std.testing.expect(!killJob(sh.pid, sh.master)); - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +test { + _ = Lsp; } -test "a command pane's child is its shell running the one line, and its exit status is read at the end" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - var got: [256]u8 = undefined; - var n: usize = 0; - while (n < got.len) { - const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); - if (r <= 0) break; // EIO once the child is gone: the pty's end - n += @intCast(r); +test "a child starts with every signal at its default and none blocked" { + var blocked = posix.sigemptyset(); + posix.sigaddset(&blocked, posix.SIG.WINCH); + posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); + defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + var was: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, &ignore, &was); + defer posix.sigaction(posix.SIG.HUP, &was, null); + const pid = libc.fork(); + if (pid == 0) { + resetChildSignals(); + var now: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, null, &now); + var mask = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.BLOCK, null, &mask); + const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); + libc._exit(if (ok) 0 else 1); } - try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); - try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); + var status: c_int = 0; + _ = libc.waitpid(pid, &status, 0); + try std.testing.expectEqual(@as(c_int, 0), status); } -test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const Case = struct { line: []const u8, status: u8 }; - // A job left in the background holds the pty open past the command's - // exit; a command that lets go of its terminal runs on past its end of - // file. Either way the exit is the process's. - for ([_]Case{ - .{ .line = "sleep 3 & exit 4", .status = 4 }, - .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, - }) |c| { - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", c.line); - while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - try std.testing.expect(watchExit(child.pid)); - var got: ?libc.pid_t = null; - var waited: i64 = 0; - while (got == null and waited < 5000) : (waited += 10) { - got = takeExited(); - if (got == null) sleepMs(10); +test "the pager's path is quoted only when it needs it" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); + try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); + try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); +} + +test "the child environment replaces the launcher's terminal identity exactly once" { + const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + if (t.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..t.len], t); + saved_buf[t.len] = 0; + break :blk saved_buf[0..t.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + + // A launcher TERM must be shadowed rather than duplicated, and the rest of + // the environment must arrive untouched. + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); + + var slots: ChildEnv.Slots = undefined; + // Where the user named no pager: a terminal's shell pages into a + // +Pager pane (`pardes -`); a command pane's through cat. A pager the + // user named is kept. + var shell_slots: ChildEnv.Slots = undefined; + const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; + var said: usize = 0; + var systemd: usize = 0; + var j: usize = 0; + while (shell_envp[j]) |entry| : (j += 1) { + const line = std.mem.span(entry); + if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; + if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; + if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { + try std.testing.expect(std.mem.endsWith(u8, line, " -")); + said += 1; + } + } + if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); + // systemd's pager and its secure mode off, with ours only. + if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) + try std.testing.expectEqual(@as(usize, 2), systemd); + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var terms: usize = 0; + var colorterms: usize = 0; + var probes: usize = 0; + var dumb = false; + var pagers: usize = 0; + var git_pagers: usize = 0; + var pager_cat = false; + var git_pager_cat = false; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; + if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; + if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; + if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; + if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; + if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; + if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; + if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; + } + // A pager only where the user named none: cat, so nothing waits in less. + try std.testing.expectEqual(@as(usize, 1), pagers); + try std.testing.expectEqual(@as(usize, 1), git_pagers); + if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); + if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); + try std.testing.expectEqual(@as(usize, 1), terms); + try std.testing.expectEqual(@as(usize, 1), colorterms); + try std.testing.expectEqual(@as(usize, 1), probes); + try std.testing.expect(!dumb); + // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it + // is a separate entry and never a second TERM. + try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); +} + +test "shell spawn rejects invalid directories before creating a child" { + const rcs: Shell.PromptFiles = .{}; + try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); + const too_long = @as([4096]u8, @splat('x')); + try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; + var path_buf: [4096]u8 = undefined; + const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); + const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); + const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); + try std.testing.expect(missing.len > 256); + try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); +} + +test "a forked shell is told which terminal it is talking to" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + // Whatever launched the test is the wrong answer, so make it a loud one. + const saved = libc.getenv("TERM"); + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + const span = std.mem.span(t); + if (span.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..span.len], span); + saved_buf[span.len] = 0; + break :blk saved_buf[0..span.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + _ = Shell.setenv("TERM", "dumb", 1); + + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + // The echoed command carries the unexpanded `$TERM`, so only the shell's + // own expansion can match this. + try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); + try std.testing.expect(sh.waitText( + "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, + 5_000, + )); +} + +test "shell spawn uses an explicit OS directory longer than 256 bytes" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(std.testing.io, sub_path); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; + try std.testing.expect(directory.len > 256); + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); + var expected_buf: [4096]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); + try std.testing.expect(sh.waitText(expected, 5_000)); +} + +test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "start/a/b"); + var path_buf: [4096]u8 = undefined; + const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; + var inner_buf: [4096]u8 = undefined; + const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; + const rcs: Shell.PromptFiles = .{}; + var result: [4096]u8 = undefined; + // A wrapper exec'd over the shell (timeout standing in for 9ns) runs + // another, two directories down, in the foreground. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); + try std.testing.expect(sh.waitText("pardes-in-", 5_000)); + // printf runs before the inner shell takes the foreground. + var tries: usize = 0; + while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) + try std.testing.io.sleep(.fromMilliseconds(20), .awake); + try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } + // A job of the shell's own, gone into a/b, leaves the pane where the + // shell is. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); + try std.testing.expect(sh.waitText("pardes-job", 5_000)); + try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } +} + +test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(io, nested); + var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; + try std.testing.expect(directory.len > 1024); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); +} + +test "a shell whose directory was removed is not named `... (deleted)`" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "gone"); + var path_buf: [4096]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [4096]u8 = undefined; + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try tmp.dir.deleteDir(io, "gone"); + try std.testing.expect(shellCwd(child.pid, &result) == null); +} + +test "the children blob parses to pids, and a garbage token never becomes one" { + var out: [8]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); + try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); + try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); + try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); + try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); + var two: [2]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); +} + +test "the process group comes off the last ')', not a comm-shifted stat field" { + const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ + "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; + try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); + try std.testing.expect(parseGroupSession("") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); + try std.testing.expect(parseGroupSession("no parens here at all") == null); +} + +test "the zombie state comes off its own status line" { + try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); + try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); + try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nSta")); + try std.testing.expect(!parseZombie("State:\t")); +} + +test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + try std.testing.expect(sh.holdsTaken(false, 200)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); +} + +test "Kill stops the foreground job, never the shell, and finds none with job control off" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + // At the prompt the shell is the foreground: there is nothing to stop. + try std.testing.expect(!killJob(sh.pid, sh.master)); + sleepMs(100); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + try std.testing.expect(killJob(sh.pid, sh.master)); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + // Job control off: the job runs in the shell's own group. + sh.forget(); + sh.send("set +m; sleep 30\n"); + sleepMs(300); + try std.testing.expect(!killJob(sh.pid, sh.master)); + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +} + +test "a command pane's child is its shell running the one line, and its exit status is read at the end" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + var got: [256]u8 = undefined; + var n: usize = 0; + while (n < got.len) { + const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); + if (r <= 0) break; // EIO once the child is gone: the pty's end + n += @intCast(r); + } + try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); + try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); +} + +test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const Case = struct { line: []const u8, status: u8 }; + // A job left in the background holds the pty open past the command's + // exit; a command that lets go of its terminal runs on past its end of + // file. Either way the exit is the process's. + for ([_]Case{ + .{ .line = "sleep 3 & exit 4", .status = 4 }, + .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + try std.testing.expect(watchExit(child.pid)); + var got: ?libc.pid_t = null; + var waited: i64 = 0; + while (got == null and waited < 5000) : (waited += 10) { + got = takeExited(); + if (got == null) sleepMs(10); } try std.testing.expectEqual(@as(?libc.pid_t, child.pid), got); // Told before it is reaped: the pid is still the child's. @@ -3581,65 +3658,6 @@ test "a full-screen program takes the tty until it quits" { if (ran == 0) return error.SkipZigTest; } -// ---- what every host's vtable does alike ---- - -/// A Save's write: the file written through the core's filesystem, the -/// pane's watch told the new text is the editor's own (so it is no outside -/// change), and "saved" said on the pane. -pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { - filesystem.write(core, path, bytes) catch |err| - return core.saveFailed(pane, path, err); - if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { - if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { - .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, - .kind => {}, - }; - }; - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); - // The init file, saved here (Config): its settings take effect now. - pardes.exec.reapplyInitFile(core, path, bytes); -} - -/// A Dump's write: into the state file under a label of its own -/// (Db.putDump), or as a file of its own where `Dump export` names one or -/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its -/// goldens). -pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { - const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; - if (to) |path| { - filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); - return core.setLastDump(path); - } - var stamp: [64]u8 = undefined; - var buf: [128]u8 = undefined; - const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { - var path: [4200]u8 = undefined; - // In the words a host reports failures in (tape.Failure). - const said: pardes.tape.Failure = switch (err) { - error.NoStateFile => error.NoDumpDirectory, - error.OutOfMemory => error.OutOfMemory, - error.NoSpaceLeft => error.NoSpaceLeft, - error.AccessDenied => error.AccessDenied, - else => error.InputOutput, - }; - return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); - }; - core.setLastDump(label); -} - -/// DumpThemes: the built-in themes written below the config directory. -pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { - const config_dir = core.opts.config_dir orelse return; - const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { - core.reportError(pane, "dump themes", err); - return; - }; - defer gpa.free(out_dir); - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); -} - test "completion survives a full output queue" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 7 }; @@ -3678,24 +3696,6 @@ test "completion survives a full output queue" { try std.testing.expectEqual(@as(usize, 0), queue.take().len); } -pub const PtyTests = struct { - pub fn waitBlocked(queue: *Inbox) !void { - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - queue.lock(); - const waiting = queue.waiting; - queue.unlock(); - if (waiting != 0) return; - try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - return error.ReaderDidNotBlock; - } - - fn tail(queue: *Inbox, bytes: []u8) void { - if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - } -}; - test "PTY backpressure retains byte order and tail before EOF" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; diff --git a/src/layout.zig b/src/layout.zig index 188ac2b8..f21eace1 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1350,6 +1350,189 @@ fn keepTerminalFloors(p: *Pardes, c: usize, hs: []u16) void { } } +// ---- the session's columns and the rows its chrome takes ---- + +/// The workspace tag's height: one row while the setting keeps it, as +/// acme's row tag is, zero once a native shell takes its commands over. +/// Layout and hit testing read this rather than the constant, the way +/// they read `columnBarHeight`. +pub fn topBarHeight(p: *const Pardes) u16 { + if (!p.settings.workspace_tag) return 0; + return TOPBAR_H; +} + +/// The column tags' height: one row, as acme's (cols.c:244, colresize, +/// gives a column tag one font height); a newline in one is a space +/// (tagline.flattenHeaders). +pub fn columnBarHeight(p: *const Pardes) u16 { + if (p.view().screen_h < 3) return 0; + return COLBAR_H; +} + +/// Newcol: an empty column right of the calling pane's, the keyboard +/// on its tag, for the next pane made to fill. +pub fn newColumn(p: *Pardes, from_id: usize) void { + // An empty window (Delcol took the last column): its first column. + if (firstColumn(p)) |c| return tagline.enterHeader(p, c); + const col = keyboardColumn(p, from_id) orelse return; + // A trial: laying it out gives it a serial (layout.compute), which a + // refusal takes back. Every other column has its own already, so + // the counter as it is now is the trial's to return to. + for (0..p.view().ncol) |k| _ = columnSerial(p, k); + const unspent = p.next_column_serial; + const before_min = minima(p); + const before = p.view().rects; + // Said, not silently nothing: "no space" is 9ns's word for ENOSPC. + const c = insertColumnUnannounced(p, col, false) orelse { + return p.reportFailure(from_id, if (p.view().ncol >= MAX_COLS) + std.fmt.comptimePrint("Newcol: no space for a column: {d} max", .{MAX_COLS}) + else + "Newcol: no space for a column: this one is too narrow to split"); + }; + if (!keepColumn(p, c, &before, &before_min)) { + p.next_column_serial = unspent; + compute(p); + return p.reportFailure(from_id, "Newcol: no space for a column: the panes' tags would not fit"); + } + // Kept: now it has a serial, and the log hears of it. + noteColumn(p, "newcol", columnSerial(p, c)); + tagline.enterHeader(p, c); +} + +pub fn setActiveColumn(p: *Pardes, c: usize) void { + if (c < p.view().ncol) p.view().active_column = columnSerial(p, c); +} + +/// The active column, while it is still there. +pub fn activeColumn(p: *const Pardes) ?usize { + return columnBySerial(p, p.view().active_column); +} + +pub fn noteTyped(p: *Pardes) void { + if (p.view().header != null) { + if (p.headerColumn()) |c| p.setActiveColumn(c); + } else if (findPane(p, p.view().active)) |f| p.setActiveColumn(f.col); +} + +/// New, run from column `c`'s tag. +pub fn newScratchIn(p: *Pardes, from_id: usize, c: usize) void { + p.exec_column = c; + defer p.exec_column = null; + p.newScratchBelow(from_id); +} + +/// The column a command acts on: the one whose tag it came from, else +/// the one whose tag has the keyboard, else `id`'s. +pub fn keyboardColumn(p: *Pardes, id: usize) ?usize { + if (p.exec_column) |c| return c; + if (p.headerColumn()) |c| return c; + return if (findPane(p, id)) |f| f.col else null; +} + +/// Delcol: close column `col` and every pane in it. +pub fn removeColumn(p: *Pardes, col: usize) !void { + const v = p.view(); + if (col >= v.ncol) return; + const had_focus = keyboardColumn(p, v.active) == col; + const beside = if (had_focus) besideColumn(p, col, if (v.header != null) null else v.rects[v.active]) else null; + var ids: [MAX_PANES]usize = undefined; + var parents: [MAX_PANES]*Pane = undefined; + const count = v.cols[col].n; + for (0..count) |i| { + ids[i] = v.cols[col].panes[i]; + parents[i] = p.panes[ids[i]].?; + } + try panes.detachCwds(p, parents[0..count]); + for (ids[0..count], parents[0..count]) |closed, pane| { + // Kept for Panes; its column goes, so it comes back as a new pane. + if (p.store.keep(p, closed)) |k| p.store.close(p, k, null); + panes.retirePane(p, pane); + removePane(p, closed); + p.panes[closed] = null; + pardes.views.gone(p, closed); + } + dropColumn(p, col); + // The last column gone, the window stays, empty but for the + // workspace tag, as acme's does; Newcol starts again from there. + if (p.panes[v.active] == null) v.active = beside orelse panes.anyPane(p) orelse return tagline.enterHeader(p, null); +} + +/// The pane that takes over the keyboard from column `col`: in the +/// column layout.dropColumn gives the width to, the one level with the +/// middle of `r` (of the screen without one). Asked while rects hold. +pub fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize { + const v = p.view(); + if (v.ncol < 2) return null; + const next = if (col > 0) col - 1 else col + 1; + const mid = if (r) |at| at.y + at.h / 2 else v.screen_h / 2; + var pick: ?usize = null; + for (v.cols[next].panes[0..p.view().cols[next].n]) |k| { + if (p.panes[k] == null) continue; + pick = k; + if (v.rects[k].y +| v.rects[k].h > mid) break; + } + return pick; +} + +/// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps +/// it: what a placement must leave it above its body rows. +pub fn wantedTagRows(p: *Pardes, id: usize) u16 { + const pane = p.panes[id] orelse return BOX_H; + if (pane.collapsed or !pane.tag_expanded) return BOX_H; + if (p.view().rects[id].w == 0) return pane.tag_rows; // never laid out + var wrap_room: [32 * 1024]u8 = undefined; + var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); + const wa = wrap_fba.allocator(); + const prefix = tagline.prefixIn(p, wa, pane) catch return pane.tag_rows; + const whole = std.mem.concat(wa, u8, &.{ prefix, tagline.curTail(pane) }) catch return pane.tag_rows; + const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch return pane.tag_rows; + return @intCast(@max(BOX_H, @min(shown.rows(), MAX_TAG_ROWS))); +} + +/// The pane's first body row, under its tag. Notice bands do NOT move it +/// -- they are an overlay, drawn over the top rows rather than taking them. +pub fn bodyTop(_: *const Pardes, pane: *const Pane, r: Rect) u16 { + return r.y + pane.tag_rows; +} + +/// The tag's first row: the pane's top. +pub fn tagTop(_: *const Pardes, _: *const Pane, r: Rect) u16 { + return r.y; +} + +pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { + const layer: Layer = .{ .kind = .pane, .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } }; + return layer.capacity(p.view().row_metrics); +} + +// ---- render: build the canonical surface (draw.zig) ---- + +/// A frontend's tag hit, if what it names is still there: resolved on +/// the place it carries (Layer.Place), not on this process's frame. +pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { + if (tag_hit.kind == .pane) { + if (tag_hit.id >= p.panes.len) return null; + const pane = p.panes[tag_hit.id] orelse return null; + if (pane.serial != tag_hit.serial) return null; + } + if (tag_hit.kind == .column and (tag_hit.id >= p.view().ncol or p.view().cols[tag_hit.id].serial != tag_hit.serial)) return null; + return Layer.tagAgain(tag_hit); +} + +/// A test's attachment: an empty +Search in a new slot, in no column. +fn testAttachment(p: *Pardes) !usize { + const free = p.freeSlot().?; + _ = try panes.Output.open(p, free, "/tmp", .search, "", try p.gpa.dupe(u8, "q\n")); + return free; +} + +/// Each column's weight, as a test compares them. +fn weightsOf(p: *const Pardes) [MAX_COLS]u64 { + var out: [MAX_COLS]u64 = undefined; + for (&out, p.view().cols) |*w, c| w.* = c.weight; + return out; +} + test "collapse transfers height upward and restores the original layout" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }); defer p.deinit(); @@ -1578,13 +1761,6 @@ test "column reorder moves only crossed state and preserves weights" { try std.testing.expectEqual(@as(i32, 21), p.view().col_tags[1].cur_col); } -/// A test's attachment: an empty +Search in a new slot, in no column. -fn testAttachment(p: *Pardes) !usize { - const free = p.freeSlot().?; - _ = try panes.Output.open(p, free, "/tmp", .search, "", try p.gpa.dupe(u8, "q\n")); - return free; -} - test "an attachment takes its rows from its owner alone, keeps them, and moves, folds and closes with it" { const exec = pardes.exec; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 48 }); @@ -1705,175 +1881,6 @@ test "an attachment survives Dump and Restore, and one left away from its owner try std.testing.expect(p.panes[t].?.attached_to == null); } -// ---- the session's columns and the rows its chrome takes ---- - -/// The workspace tag's height: one row while the setting keeps it, as -/// acme's row tag is, zero once a native shell takes its commands over. -/// Layout and hit testing read this rather than the constant, the way -/// they read `columnBarHeight`. -pub fn topBarHeight(p: *const Pardes) u16 { - if (!p.settings.workspace_tag) return 0; - return TOPBAR_H; -} - -/// The column tags' height: one row, as acme's (cols.c:244, colresize, -/// gives a column tag one font height); a newline in one is a space -/// (tagline.flattenHeaders). -pub fn columnBarHeight(p: *const Pardes) u16 { - if (p.view().screen_h < 3) return 0; - return COLBAR_H; -} - -/// Newcol: an empty column right of the calling pane's, the keyboard -/// on its tag, for the next pane made to fill. -pub fn newColumn(p: *Pardes, from_id: usize) void { - // An empty window (Delcol took the last column): its first column. - if (firstColumn(p)) |c| return tagline.enterHeader(p, c); - const col = keyboardColumn(p, from_id) orelse return; - // A trial: laying it out gives it a serial (layout.compute), which a - // refusal takes back. Every other column has its own already, so - // the counter as it is now is the trial's to return to. - for (0..p.view().ncol) |k| _ = columnSerial(p, k); - const unspent = p.next_column_serial; - const before_min = minima(p); - const before = p.view().rects; - // Said, not silently nothing: "no space" is 9ns's word for ENOSPC. - const c = insertColumnUnannounced(p, col, false) orelse { - return p.reportFailure(from_id, if (p.view().ncol >= MAX_COLS) - std.fmt.comptimePrint("Newcol: no space for a column: {d} max", .{MAX_COLS}) - else - "Newcol: no space for a column: this one is too narrow to split"); - }; - if (!keepColumn(p, c, &before, &before_min)) { - p.next_column_serial = unspent; - compute(p); - return p.reportFailure(from_id, "Newcol: no space for a column: the panes' tags would not fit"); - } - // Kept: now it has a serial, and the log hears of it. - noteColumn(p, "newcol", columnSerial(p, c)); - tagline.enterHeader(p, c); -} - -pub fn setActiveColumn(p: *Pardes, c: usize) void { - if (c < p.view().ncol) p.view().active_column = columnSerial(p, c); -} - -/// The active column, while it is still there. -pub fn activeColumn(p: *const Pardes) ?usize { - return columnBySerial(p, p.view().active_column); -} - -pub fn noteTyped(p: *Pardes) void { - if (p.view().header != null) { - if (p.headerColumn()) |c| p.setActiveColumn(c); - } else if (findPane(p, p.view().active)) |f| p.setActiveColumn(f.col); -} - -/// New, run from column `c`'s tag. -pub fn newScratchIn(p: *Pardes, from_id: usize, c: usize) void { - p.exec_column = c; - defer p.exec_column = null; - p.newScratchBelow(from_id); -} - -/// The column a command acts on: the one whose tag it came from, else -/// the one whose tag has the keyboard, else `id`'s. -pub fn keyboardColumn(p: *Pardes, id: usize) ?usize { - if (p.exec_column) |c| return c; - if (p.headerColumn()) |c| return c; - return if (findPane(p, id)) |f| f.col else null; -} - -/// Delcol: close column `col` and every pane in it. -pub fn removeColumn(p: *Pardes, col: usize) !void { - const v = p.view(); - if (col >= v.ncol) return; - const had_focus = keyboardColumn(p, v.active) == col; - const beside = if (had_focus) besideColumn(p, col, if (v.header != null) null else v.rects[v.active]) else null; - var ids: [MAX_PANES]usize = undefined; - var parents: [MAX_PANES]*Pane = undefined; - const count = v.cols[col].n; - for (0..count) |i| { - ids[i] = v.cols[col].panes[i]; - parents[i] = p.panes[ids[i]].?; - } - try panes.detachCwds(p, parents[0..count]); - for (ids[0..count], parents[0..count]) |closed, pane| { - // Kept for Panes; its column goes, so it comes back as a new pane. - if (p.store.keep(p, closed)) |k| p.store.close(p, k, null); - panes.retirePane(p, pane); - removePane(p, closed); - p.panes[closed] = null; - pardes.views.gone(p, closed); - } - dropColumn(p, col); - // The last column gone, the window stays, empty but for the - // workspace tag, as acme's does; Newcol starts again from there. - if (p.panes[v.active] == null) v.active = beside orelse panes.anyPane(p) orelse return tagline.enterHeader(p, null); -} - -/// The pane that takes over the keyboard from column `col`: in the -/// column layout.dropColumn gives the width to, the one level with the -/// middle of `r` (of the screen without one). Asked while rects hold. -pub fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize { - const v = p.view(); - if (v.ncol < 2) return null; - const next = if (col > 0) col - 1 else col + 1; - const mid = if (r) |at| at.y + at.h / 2 else v.screen_h / 2; - var pick: ?usize = null; - for (v.cols[next].panes[0..p.view().cols[next].n]) |k| { - if (p.panes[k] == null) continue; - pick = k; - if (v.rects[k].y +| v.rects[k].h > mid) break; - } - return pick; -} - -/// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps -/// it: what a placement must leave it above its body rows. -pub fn wantedTagRows(p: *Pardes, id: usize) u16 { - const pane = p.panes[id] orelse return BOX_H; - if (pane.collapsed or !pane.tag_expanded) return BOX_H; - if (p.view().rects[id].w == 0) return pane.tag_rows; // never laid out - var wrap_room: [32 * 1024]u8 = undefined; - var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); - const wa = wrap_fba.allocator(); - const prefix = tagline.prefixIn(p, wa, pane) catch return pane.tag_rows; - const whole = std.mem.concat(wa, u8, &.{ prefix, tagline.curTail(pane) }) catch return pane.tag_rows; - const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch return pane.tag_rows; - return @intCast(@max(BOX_H, @min(shown.rows(), MAX_TAG_ROWS))); -} - -/// The pane's first body row, under its tag. Notice bands do NOT move it -/// -- they are an overlay, drawn over the top rows rather than taking them. -pub fn bodyTop(_: *const Pardes, pane: *const Pane, r: Rect) u16 { - return r.y + pane.tag_rows; -} - -/// The tag's first row: the pane's top. -pub fn tagTop(_: *const Pardes, _: *const Pane, r: Rect) u16 { - return r.y; -} - -pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { - const layer: Layer = .{ .kind = .pane, .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } }; - return layer.capacity(p.view().row_metrics); -} - -// ---- render: build the canonical surface (draw.zig) ---- - -/// A frontend's tag hit, if what it names is still there: resolved on -/// the place it carries (Layer.Place), not on this process's frame. -pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { - if (tag_hit.kind == .pane) { - if (tag_hit.id >= p.panes.len) return null; - const pane = p.panes[tag_hit.id] orelse return null; - if (pane.serial != tag_hit.serial) return null; - } - if (tag_hit.kind == .column and (tag_hit.id >= p.view().ncol or p.view().cols[tag_hit.id].serial != tag_hit.serial)) return null; - return Layer.tagAgain(tag_hit); -} - test "a new column takes width only from the column that created it" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 124, .rows = 24 }); defer p.deinit(); @@ -2033,10 +2040,3 @@ test "tiny screens keep pane space before adding a column tag" { try std.testing.expectEqual(TOPBAR_H, p.view().rects[0].y); _ = try p.render(p.scratch.allocator()); } - -/// Each column's weight, as a test compares them. -fn weightsOf(p: *const Pardes) [MAX_COLS]u64 { - var out: [MAX_COLS]u64 = undefined; - for (&out, p.view().cols) |*w, c| w.* = c.weight; - return out; -} diff --git a/src/locations.zig b/src/locations.zig index f6a0cf9c..fc39f92d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -646,20 +646,6 @@ fn appendContext(arena: std.mem.Allocator, rows: *std.ArrayList(Pending), path: }); } -test "locations tab delimiter preserves source indentation and spaced paths" { - const row = parse("some directory/界.zig:12:3-5 \t\t value"); - try std.testing.expectEqualStrings("some directory/界.zig", row.path); - try std.testing.expectEqual(@as(usize, 12), row.at.line); - try std.testing.expectEqualStrings("\t value", "some directory/界.zig:12:3-5 \t\t value"[row.code_start..]); -} - -test "locations native results retain the first source tab" { - const text = "some directory/a.zig:3:2 \t value"; - const row = parseRaw(text); - try std.testing.expectEqualStrings("some directory/a.zig", row.path); - try std.testing.expectEqualStrings("\t value", text[row.code_start..]); -} - // ---- the Locations setting ---- pub const Config = struct { @@ -712,32 +698,6 @@ pub const Config = struct { } }; -test "LocationsConfig reflection round trip and partial updates" { - var config: Config = .{}; - config = try config.parse("context:5 tscontext:on"); - config = try config.parse("tslocations:off"); - try std.testing.expectEqual(Config{ .context = 5, .tscontext = true, .tslocations = false }, config); - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - try config.write(&out.writer); - try std.testing.expectEqualStrings("context:5 tscontext:on tslocations:off layout:stacked", out.written()); - try std.testing.expectEqual(config, try (Config{}).parse(out.written())); - try std.testing.expectEqual(config, try config.parse(" \n\t")); - try std.testing.expectEqual(@as(u16, 2), (try config.parse("context:1 context:2")).context); - try std.testing.expectEqual(Config.Layout.@"inline", (try config.parse("layout:inline")).layout); -} - -test "LocationsConfig rejects invalid updates atomically" { - const config: Config = .{ .context = 3, .tscontext = true }; - try std.testing.expectError(error.UnknownLocationSetting, config.parse("context:5 unknown:on")); - try std.testing.expectError(error.ExpectedOnOrOff, config.parse("context:5 tscontext:true")); - try std.testing.expectError(error.ExpectedKeyValue, config.parse("context")); - try std.testing.expectError(error.InvalidLayout, config.parse("context:5 layout:sideways")); - for ([_][]const u8{ "context:", "context:-1", "context:65536", "context:five" }) |input| - try std.testing.expectError(error.InvalidContext, config.parse(input)); - try std.testing.expectEqual(@as(u16, 3), config.context); -} - // ---- the analysis cache ---- /// Owned source snapshots keep analysis valid across filesystem changes and @@ -890,6 +850,46 @@ pub const Cache = struct { } }; +test "locations tab delimiter preserves source indentation and spaced paths" { + const row = parse("some directory/界.zig:12:3-5 \t\t value"); + try std.testing.expectEqualStrings("some directory/界.zig", row.path); + try std.testing.expectEqual(@as(usize, 12), row.at.line); + try std.testing.expectEqualStrings("\t value", "some directory/界.zig:12:3-5 \t\t value"[row.code_start..]); +} + +test "locations native results retain the first source tab" { + const text = "some directory/a.zig:3:2 \t value"; + const row = parseRaw(text); + try std.testing.expectEqualStrings("some directory/a.zig", row.path); + try std.testing.expectEqualStrings("\t value", text[row.code_start..]); +} + +test "LocationsConfig reflection round trip and partial updates" { + var config: Config = .{}; + config = try config.parse("context:5 tscontext:on"); + config = try config.parse("tslocations:off"); + try std.testing.expectEqual(Config{ .context = 5, .tscontext = true, .tslocations = false }, config); + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try config.write(&out.writer); + try std.testing.expectEqualStrings("context:5 tscontext:on tslocations:off layout:stacked", out.written()); + try std.testing.expectEqual(config, try (Config{}).parse(out.written())); + try std.testing.expectEqual(config, try config.parse(" \n\t")); + try std.testing.expectEqual(@as(u16, 2), (try config.parse("context:1 context:2")).context); + try std.testing.expectEqual(Config.Layout.@"inline", (try config.parse("layout:inline")).layout); +} + +test "LocationsConfig rejects invalid updates atomically" { + const config: Config = .{ .context = 3, .tscontext = true }; + try std.testing.expectError(error.UnknownLocationSetting, config.parse("context:5 unknown:on")); + try std.testing.expectError(error.ExpectedOnOrOff, config.parse("context:5 tscontext:true")); + try std.testing.expectError(error.ExpectedKeyValue, config.parse("context")); + try std.testing.expectError(error.InvalidLayout, config.parse("context:5 layout:sideways")); + for ([_][]const u8{ "context:", "context:-1", "context:65536", "context:five" }) |input| + try std.testing.expectError(error.InvalidContext, config.parse(input)); + try std.testing.expectEqual(@as(u16, 3), config.context); +} + test "locations cache validates exact source and path and upgrades analysis" { const gpa = std.testing.allocator; syntax.start(gpa); diff --git a/src/look.zig b/src/look.zig index 7f76602e..e6b0c4ad 100644 --- a/src/look.zig +++ b/src/look.zig @@ -109,69 +109,6 @@ pub fn parsePathLine(tok: []const u8) struct { path: []const u8, at: Spot, end: return .{ .path = tok, .at = .{}, .end = tok.len }; } -test "parsePathLine: spots, ranges, and the paths that merely look like them" { - const cases = [_]struct { tok: []const u8, path: []const u8, at: Spot }{ - .{ .tok = "main.zig", .path = "main.zig", .at = .{} }, - .{ .tok = "main.zig:100", .path = "main.zig", .at = .{ .line = 100 } }, - .{ .tok = "main.zig:100:", .path = "main.zig", .at = .{ .line = 100 } }, - .{ .tok = "main.zig:100:7", .path = "main.zig", .at = .{ .line = 100, .col = 7 } }, - .{ .tok = "main.zig:100-104", .path = "main.zig", .at = .{ .line = 100, .end_line = 104 } }, - .{ .tok = "main.zig:100:7-21", .path = "main.zig", .at = .{ .line = 100, .col = 7, .end_line = 100, .end_col = 21 } }, - .{ .tok = "main.zig:100:7-104:3", .path = "main.zig", .at = .{ .line = 100, .col = 7, .end_line = 104, .end_col = 3 } }, - .{ .tok = "my-file.zig", .path = "my-file.zig", .at = .{} }, - .{ .tok = "my-file:10", .path = "my-file", .at = .{ .line = 10 } }, - .{ .tok = "x:1-y", .path = "x:1-y", .at = .{} }, - .{ .tok = "a-b-c", .path = "a-b-c", .at = .{} }, - .{ .tok = "2026-07-30", .path = "2026-07-30", .at = .{} }, - .{ .tok = "main.zig:100x", .path = "main.zig:100x", .at = .{} }, - .{ .tok = "main.zig:100:7x", .path = "main.zig", .at = .{ .line = 100 } }, - }; - for (cases) |c| { - const got = parsePathLine(c.tok); - try std.testing.expectEqualStrings(c.path, got.path); - try std.testing.expectEqual(c.at, got.at); - } -} - -test "a number too big to be a line saturates instead of taking the editor down" { - const huge = "99999999999999999999999999"; - const cases = [_][]const u8{ - "f.zig:" ++ huge, - "f.zig:" ++ huge ++ ":" ++ huge, - "f.zig:1-" ++ huge, - "f.zig:1:2-" ++ huge ++ ":" ++ huge, - }; - for (cases) |tok| { - const got = parsePathLine(tok); - try std.testing.expectEqualStrings("f.zig", got.path); - try std.testing.expect(got.at.line >= 1); - } - - var realbuf: [4096]u8 = undefined; - const target = resolve(null, "@p" ++ huge, "/tmp", &realbuf); - try std.testing.expect(target == .pane); - try std.testing.expect(target.pane.id >= 16); -} - -test "parsePathLine: `end` separates a whole-token target from a lenient read" { - for ([_][]const u8{ - "main.zig", "main.zig:100", "main.zig:100:7", - "main.zig:100-104", "main.zig:100:7-21", "main.zig:100:7-104:3", - "@p3:10:5", "x:1-y", - }) |tok| try std.testing.expectEqual(tok.len, parsePathLine(tok).end); - const partial = [_]struct { tok: []const u8, end: usize }{ - .{ .tok = "main.zig:100:", .end = "main.zig:100".len }, // trailing ':' is peeled, not parsed - .{ .tok = "main.zig:100:7x", .end = "main.zig:100".len }, - .{ .tok = "main.zig:100:7 fn main() void {", .end = "main.zig:100".len }, - .{ .tok = "main.zig:100:7-21 const x = 1;", .end = "main.zig:100:7-21".len }, - .{ .tok = "@p3:10:5 /home/goblin", .end = "@p3:10".len }, - }; - for (partial) |c| try std.testing.expectEqual(c.end, parsePathLine(c.tok).end); - const whole = "main.zig:100-104 whole lines"; - try std.testing.expectEqual(whole.len, parsePathLine(whole).end); - try std.testing.expectEqualStrings(whole, parsePathLine(whole).path); -} - pub const FileTarget = struct { path: []const u8, at: Spot, @@ -205,30 +142,6 @@ pub fn wordSpan(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, realbuf: return .{ .start = 0, .end = word.len }; } -test "lookableSpan peels prose punctuation off a path, largest first" { - if (!platform_has_fs) return; - var realbuf: [4096]u8 = undefined; - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "src/look.zig".len }), - wordSpan(null, "src/look.zig", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 1, .end = 1 + "src/look.zig".len }), - wordSpan(null, "(src/look.zig),", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "src/look.zig:12:3".len }), - wordSpan(null, "src/look.zig:12:3,", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "src/look.zig:12".len }), - wordSpan(null, "src/look.zig:12:", ".", &realbuf), - ); - try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "nothing-here", ".", &realbuf)); - try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "", ".", &realbuf)); - try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "((()))", ".", &realbuf)); -} - pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf: *[4096]u8) ?Span { var lo: usize = 0; while (lo < line.len and (line[lo] == ' ' or line[lo] == '\t')) lo += 1; @@ -251,59 +164,6 @@ pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf: return null; } -test "lookableLineSpan takes the row's location and stops before its text" { - if (!platform_has_fs) return; - var realbuf: [4096]u8 = undefined; - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "src/look.zig:12:5-9".len }), - lineSpan(null, "src/look.zig:12:5-9 const std = @import(\"std\");", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "src/look.zig:12:5".len }), - lineSpan(null, "src/look.zig:12:5 pub fn resolve", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "@p3:10:5".len }), - lineSpan(null, "@p3:10:5 /home/goblin", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 3, .end = 3 + "src/look.zig".len }), - lineSpan(null, " (src/look.zig)", ".", &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "https://pardes.dev/a".len }), - lineSpan(null, "https://pardes.dev/a Chapter One", ".", &realbuf), - ); - try std.testing.expectEqual( - @as(?Span, null), - lineSpan(null, "see also src/look.zig", ".", &realbuf), - ); - try std.testing.expectEqual(@as(?Span, null), lineSpan(null, " ", ".", &realbuf)); - try std.testing.expectEqual(@as(?Span, null), lineSpan(null, "", ".", &realbuf)); -} - -test "lookableLineSpan prefers the longest run, so a blank inside a path is one span" { - if (!platform_has_fs) return; - var realbuf: [4096]u8 = undefined; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const name = "pardes look span.txt"; - try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "" }); - try tmp.dir.createDir(io, "subdir", .default_dir); - var path: [4096]u8 = undefined; - const len = try tmp.dir.realPathFile(io, name, &path); - const cwd = std.Io.Dir.path.dirname(path[0..len]).?; - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = name.len }), - lineSpan(null, name, cwd, &realbuf), - ); - try std.testing.expectEqualDeep( - @as(?Span, .{ .start = 0, .end = "subdir".len }), - lineSpan(null, "subdir holds pardes look span.txt", cwd, &realbuf), - ); -} - /// Where a `Plumb` rule sends what it matched: the targets the built-in /// rules below make (url: the browser, through `xdg-open`), or a loaded /// kind by its name (`image`, `pdf`). @@ -558,7 +418,6 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } - const SearchStart = enum { top, cursor }; pub fn submitSearch(p: *Pardes, id: usize) void { @@ -1148,17 +1007,6 @@ fn missText(text: []const u8, buf: *[miss_path_cap + "…".len]u8) []const u8 { return pardes.ctlfs.fitErr(text, buf[0..miss_path_cap]); } -test "a miss names a long path by its start and its end, its middle given up to …" { - var cut: [miss_path_cap + "…".len]u8 = undefined; - const long = "/home/someone/" ++ std.mem.asBytes(&@as([80][5]u8, @splat("deep/".*))) ++ "the-file.zig"; - const said = missText(long, &cut); - try std.testing.expect(said.len <= miss_path_cap); - try std.testing.expect(std.mem.startsWith(u8, said, "/home/someone/")); - try std.testing.expect(std.mem.endsWith(u8, said, "/the-file.zig")); - try std.testing.expect(std.mem.indexOf(u8, said, "…") != null); - try std.testing.expectEqualStrings("short/path.txt", missText("short/path.txt", &cut)); -} - /// A file that is there but would not open: said with its path, `look: /// : permission denied`, the path cut in its middle when long. fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { @@ -1205,16 +1053,6 @@ fn zeroColumnTail(text: []const u8) bool { return false; } -test "a zero column ends a look's text, line 0 included" { - for ([_][]const u8{ "f.txt:0:0", "f.txt:3:0", "dir/f.txt:3:2-0" }) |t| try std.testing.expect(zeroColumnTail(t)); - for ([_][]const u8{ "f.txt:3", "f.txt:3:1", "f.txt:0", "f.txt", "a:b:0x" }) |t| try std.testing.expect(!zeroColumnTail(t)); -} - -test "a zero column after a path is found, in every spelling a look takes" { - for ([_][]const u8{ ":3:0", ":3:0-4", ":3:2-0", ":3:2-5:0" }) |rest| try std.testing.expect(zeroColumn(rest)); - for ([_][]const u8{ "", ":3", ":3:1", ":3:2-5", ":3:2-5:7", ":30:10" }) |rest| try std.testing.expect(!zeroColumn(rest)); -} - fn missed(p: *Pardes, id: usize, comptime fmt: []const u8, args: anytype) void { p.look_missed = true; var said: Kind.Buf(miss_path_cap + 64) = .{}; @@ -1361,16 +1199,6 @@ fn isCommitHash(word: []const u8) bool { return digit and letter; } -test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { - try std.testing.expect(isCommitHash("9bffa7041c")); - try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); - try std.testing.expect(!isCommitHash("9bffa7")); - try std.testing.expect(!isCommitHash("defaced")); - try std.testing.expect(!isCommitHash("1234567")); - try std.testing.expect(!isCommitHash("0x9bffa7041c")); - try std.testing.expect(!isCommitHash("9BFFA7041C")); -} - /// Opens (or finds) `path` as Look would, `id`'s own pane when it is empty, /// and selects what `expr` addresses there from its dot. An address that /// does not evaluate moves nothing and says why (acme: no jump). @@ -1842,6 +1670,229 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { } } +// A diff pane on `diff_text`, saved as change.diff in a fresh directory +// that holds `files` (path, content) and, if `repo`, a `.git`. +const DiffFixture = struct { + tmp: std.testing.TmpDir, + dir: []const u8, + dir_buf: [4096]u8 = undefined, + + fn init(f: *DiffFixture, repo: bool, files: []const [2][]const u8, diff_text: []const u8) !void { + const io = std.testing.io; + f.tmp = std.testing.tmpDir(.{}); + errdefer f.tmp.cleanup(); + if (repo) try f.tmp.dir.createDir(io, ".git", .default_dir); + for (files) |file| { + if (std.Io.Dir.path.dirname(file[0])) |sub| try f.tmp.dir.createDirPath(io, sub); + try f.tmp.dir.writeFile(io, .{ .sub_path = file[0], .data = file[1] }); + } + try f.tmp.dir.writeFile(io, .{ .sub_path = "change.diff", .data = diff_text }); + const len = try f.tmp.dir.realPathFile(io, "change.diff", &f.dir_buf); + f.dir = std.Io.Dir.path.dirname(f.dir_buf[0..len]).?; + } + + fn open(f: *DiffFixture, p: *Pardes, diff_text: []const u8) !*Pane { + const pane = try p.setTestFile(diff_text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ f.dir, "change.diff" }); + return pane; + } + + /// A right click's look at `row` of the diff pane (slot 0): the look + /// of the address that line names. + fn click(p: *Pardes, diff_pane: *Pane, row: usize) void { + p.view().active = 0; + const lines = diffLines(p, diff_pane).?; + var buf: [4096]u8 = undefined; + p.look_missed = false; + lookAt(p, 0, diffAddress(diff_pane, lines, row, &buf).?); + } +}; + +/// The rows n/N's walk over look-able text reads before it stops (look.zig). +pub const max_look_rows = 8192; + +fn expectAt(p: *Pardes, suffix: []const u8, line: usize) !void { + const pane = p.panes[p.view().active].?; + const f = pane.file orelse return error.NoFileOpened; + if (!std.mem.endsWith(u8, f.path, suffix)) { + std.debug.print("opened {s}, not {s}\n", .{ f.path, suffix }); + return error.WrongFile; + } + try std.testing.expectEqual(@as(i32, @intCast(line)) - 1, pane.body.cur_row); +} + +test "parsePathLine: spots, ranges, and the paths that merely look like them" { + const cases = [_]struct { tok: []const u8, path: []const u8, at: Spot }{ + .{ .tok = "main.zig", .path = "main.zig", .at = .{} }, + .{ .tok = "main.zig:100", .path = "main.zig", .at = .{ .line = 100 } }, + .{ .tok = "main.zig:100:", .path = "main.zig", .at = .{ .line = 100 } }, + .{ .tok = "main.zig:100:7", .path = "main.zig", .at = .{ .line = 100, .col = 7 } }, + .{ .tok = "main.zig:100-104", .path = "main.zig", .at = .{ .line = 100, .end_line = 104 } }, + .{ .tok = "main.zig:100:7-21", .path = "main.zig", .at = .{ .line = 100, .col = 7, .end_line = 100, .end_col = 21 } }, + .{ .tok = "main.zig:100:7-104:3", .path = "main.zig", .at = .{ .line = 100, .col = 7, .end_line = 104, .end_col = 3 } }, + .{ .tok = "my-file.zig", .path = "my-file.zig", .at = .{} }, + .{ .tok = "my-file:10", .path = "my-file", .at = .{ .line = 10 } }, + .{ .tok = "x:1-y", .path = "x:1-y", .at = .{} }, + .{ .tok = "a-b-c", .path = "a-b-c", .at = .{} }, + .{ .tok = "2026-07-30", .path = "2026-07-30", .at = .{} }, + .{ .tok = "main.zig:100x", .path = "main.zig:100x", .at = .{} }, + .{ .tok = "main.zig:100:7x", .path = "main.zig", .at = .{ .line = 100 } }, + }; + for (cases) |c| { + const got = parsePathLine(c.tok); + try std.testing.expectEqualStrings(c.path, got.path); + try std.testing.expectEqual(c.at, got.at); + } +} + +test "a number too big to be a line saturates instead of taking the editor down" { + const huge = "99999999999999999999999999"; + const cases = [_][]const u8{ + "f.zig:" ++ huge, + "f.zig:" ++ huge ++ ":" ++ huge, + "f.zig:1-" ++ huge, + "f.zig:1:2-" ++ huge ++ ":" ++ huge, + }; + for (cases) |tok| { + const got = parsePathLine(tok); + try std.testing.expectEqualStrings("f.zig", got.path); + try std.testing.expect(got.at.line >= 1); + } + + var realbuf: [4096]u8 = undefined; + const target = resolve(null, "@p" ++ huge, "/tmp", &realbuf); + try std.testing.expect(target == .pane); + try std.testing.expect(target.pane.id >= 16); +} + +test "parsePathLine: `end` separates a whole-token target from a lenient read" { + for ([_][]const u8{ + "main.zig", "main.zig:100", "main.zig:100:7", + "main.zig:100-104", "main.zig:100:7-21", "main.zig:100:7-104:3", + "@p3:10:5", "x:1-y", + }) |tok| try std.testing.expectEqual(tok.len, parsePathLine(tok).end); + const partial = [_]struct { tok: []const u8, end: usize }{ + .{ .tok = "main.zig:100:", .end = "main.zig:100".len }, // trailing ':' is peeled, not parsed + .{ .tok = "main.zig:100:7x", .end = "main.zig:100".len }, + .{ .tok = "main.zig:100:7 fn main() void {", .end = "main.zig:100".len }, + .{ .tok = "main.zig:100:7-21 const x = 1;", .end = "main.zig:100:7-21".len }, + .{ .tok = "@p3:10:5 /home/goblin", .end = "@p3:10".len }, + }; + for (partial) |c| try std.testing.expectEqual(c.end, parsePathLine(c.tok).end); + const whole = "main.zig:100-104 whole lines"; + try std.testing.expectEqual(whole.len, parsePathLine(whole).end); + try std.testing.expectEqualStrings(whole, parsePathLine(whole).path); +} + +test "lookableSpan peels prose punctuation off a path, largest first" { + if (!platform_has_fs) return; + var realbuf: [4096]u8 = undefined; + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "src/look.zig".len }), + wordSpan(null, "src/look.zig", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 1, .end = 1 + "src/look.zig".len }), + wordSpan(null, "(src/look.zig),", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "src/look.zig:12:3".len }), + wordSpan(null, "src/look.zig:12:3,", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "src/look.zig:12".len }), + wordSpan(null, "src/look.zig:12:", ".", &realbuf), + ); + try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "nothing-here", ".", &realbuf)); + try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "", ".", &realbuf)); + try std.testing.expectEqual(@as(?Span, null), wordSpan(null, "((()))", ".", &realbuf)); +} + +test "lookableLineSpan takes the row's location and stops before its text" { + if (!platform_has_fs) return; + var realbuf: [4096]u8 = undefined; + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "src/look.zig:12:5-9".len }), + lineSpan(null, "src/look.zig:12:5-9 const std = @import(\"std\");", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "src/look.zig:12:5".len }), + lineSpan(null, "src/look.zig:12:5 pub fn resolve", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "@p3:10:5".len }), + lineSpan(null, "@p3:10:5 /home/goblin", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 3, .end = 3 + "src/look.zig".len }), + lineSpan(null, " (src/look.zig)", ".", &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "https://pardes.dev/a".len }), + lineSpan(null, "https://pardes.dev/a Chapter One", ".", &realbuf), + ); + try std.testing.expectEqual( + @as(?Span, null), + lineSpan(null, "see also src/look.zig", ".", &realbuf), + ); + try std.testing.expectEqual(@as(?Span, null), lineSpan(null, " ", ".", &realbuf)); + try std.testing.expectEqual(@as(?Span, null), lineSpan(null, "", ".", &realbuf)); +} + +test "lookableLineSpan prefers the longest run, so a blank inside a path is one span" { + if (!platform_has_fs) return; + var realbuf: [4096]u8 = undefined; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const name = "pardes look span.txt"; + try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "" }); + try tmp.dir.createDir(io, "subdir", .default_dir); + var path: [4096]u8 = undefined; + const len = try tmp.dir.realPathFile(io, name, &path); + const cwd = std.Io.Dir.path.dirname(path[0..len]).?; + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = name.len }), + lineSpan(null, name, cwd, &realbuf), + ); + try std.testing.expectEqualDeep( + @as(?Span, .{ .start = 0, .end = "subdir".len }), + lineSpan(null, "subdir holds pardes look span.txt", cwd, &realbuf), + ); +} + +test "a miss names a long path by its start and its end, its middle given up to …" { + var cut: [miss_path_cap + "…".len]u8 = undefined; + const long = "/home/someone/" ++ std.mem.asBytes(&@as([80][5]u8, @splat("deep/".*))) ++ "the-file.zig"; + const said = missText(long, &cut); + try std.testing.expect(said.len <= miss_path_cap); + try std.testing.expect(std.mem.startsWith(u8, said, "/home/someone/")); + try std.testing.expect(std.mem.endsWith(u8, said, "/the-file.zig")); + try std.testing.expect(std.mem.indexOf(u8, said, "…") != null); + try std.testing.expectEqualStrings("short/path.txt", missText("short/path.txt", &cut)); +} + +test "a zero column ends a look's text, line 0 included" { + for ([_][]const u8{ "f.txt:0:0", "f.txt:3:0", "dir/f.txt:3:2-0" }) |t| try std.testing.expect(zeroColumnTail(t)); + for ([_][]const u8{ "f.txt:3", "f.txt:3:1", "f.txt:0", "f.txt", "a:b:0x" }) |t| try std.testing.expect(!zeroColumnTail(t)); +} + +test "a zero column after a path is found, in every spelling a look takes" { + for ([_][]const u8{ ":3:0", ":3:0-4", ":3:2-0", ":3:2-5:0" }) |rest| try std.testing.expect(zeroColumn(rest)); + for ([_][]const u8{ "", ":3", ":3:1", ":3:2-5", ":3:2-5:7", ":30:10" }) |rest| try std.testing.expect(!zeroColumn(rest)); +} + +test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { + try std.testing.expect(isCommitHash("9bffa7041c")); + try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); + try std.testing.expect(!isCommitHash("9bffa7")); + try std.testing.expect(!isCommitHash("defaced")); + try std.testing.expect(!isCommitHash("1234567")); + try std.testing.expect(!isCommitHash("0x9bffa7041c")); + try std.testing.expect(!isCommitHash("9BFFA7041C")); +} + test "Look hover waits without mutating the pane and input cancels it" { const delay = config.look_preview_delay_frames; @@ -2037,55 +2088,6 @@ test "a pointer resting where a look-hover found nothing does not wake the core try std.testing.expect(p.look_hover_wait == null and p.look_hover_preview == null); } -// A diff pane on `diff_text`, saved as change.diff in a fresh directory -// that holds `files` (path, content) and, if `repo`, a `.git`. -const DiffFixture = struct { - tmp: std.testing.TmpDir, - dir: []const u8, - dir_buf: [4096]u8 = undefined, - - fn init(f: *DiffFixture, repo: bool, files: []const [2][]const u8, diff_text: []const u8) !void { - const io = std.testing.io; - f.tmp = std.testing.tmpDir(.{}); - errdefer f.tmp.cleanup(); - if (repo) try f.tmp.dir.createDir(io, ".git", .default_dir); - for (files) |file| { - if (std.Io.Dir.path.dirname(file[0])) |sub| try f.tmp.dir.createDirPath(io, sub); - try f.tmp.dir.writeFile(io, .{ .sub_path = file[0], .data = file[1] }); - } - try f.tmp.dir.writeFile(io, .{ .sub_path = "change.diff", .data = diff_text }); - const len = try f.tmp.dir.realPathFile(io, "change.diff", &f.dir_buf); - f.dir = std.Io.Dir.path.dirname(f.dir_buf[0..len]).?; - } - - fn open(f: *DiffFixture, p: *Pardes, diff_text: []const u8) !*Pane { - const pane = try p.setTestFile(diff_text); - p.gpa.free(pane.file.?.path); - pane.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ f.dir, "change.diff" }); - return pane; - } - - /// A right click's look at `row` of the diff pane (slot 0): the look - /// of the address that line names. - fn click(p: *Pardes, diff_pane: *Pane, row: usize) void { - p.view().active = 0; - const lines = diffLines(p, diff_pane).?; - var buf: [4096]u8 = undefined; - p.look_missed = false; - lookAt(p, 0, diffAddress(diff_pane, lines, row, &buf).?); - } -}; - -fn expectAt(p: *Pardes, suffix: []const u8, line: usize) !void { - const pane = p.panes[p.view().active].?; - const f = pane.file orelse return error.NoFileOpened; - if (!std.mem.endsWith(u8, f.path, suffix)) { - std.debug.print("opened {s}, not {s}\n", .{ f.path, suffix }); - return error.WrongFile; - } - try std.testing.expectEqual(@as(i32, @intCast(line)) - 1, pane.body.cur_row); -} - test "Look on each kind of diff line opens the new file at the line it names" { if (!platform_has_fs) return; const numbered = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n" ++ @@ -2666,9 +2668,6 @@ test "Look on a diff line is the look of the address it names, selected by hand: try std.testing.expectEqual(@as(i32, 1), seen[0].row); } -/// The rows n/N's walk over look-able text reads before it stops (look.zig). -pub const max_look_rows = 8192; - test "Plumb: the user's rules come before the built-in ones, the first that matches wins, a bad rule is refused, a dump keeps them" { if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index eefa27c9..3f8fcde3 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -80,17 +80,6 @@ pub fn explaining(req: Req) Req { return r; } -test "an explain request narrates the query named in its arg, a definition by default" { - const base: Req = .{ .kind = .explain, .path = "/x.zig", .source = "", .offset = 0 }; - var r = base; - r.arg = "hover "; - try std.testing.expectEqual(Kind.hover, explaining(r).explains); - r.arg = "rename newName"; - try std.testing.expectEqual(Kind.rename, explaining(r).explains); - try std.testing.expectEqualStrings("newName", explaining(r).arg); - try std.testing.expectEqual(Kind.definition, explaining(base).explains); -} - /// Every language, Zig's (zls) included, through the protocol client, which /// runs its server as a child process. const client = @import("lsp_client.zig"); @@ -167,6 +156,17 @@ pub fn lineCol(source: []const u8, offset: usize) struct { line: usize, col: usi return .{ .line = line, .col = upto.len - bol }; } +test "an explain request narrates the query named in its arg, a definition by default" { + const base: Req = .{ .kind = .explain, .path = "/x.zig", .source = "", .offset = 0 }; + var r = base; + r.arg = "hover "; + try std.testing.expectEqual(Kind.hover, explaining(r).explains); + r.arg = "rename newName"; + try std.testing.expectEqual(Kind.rename, explaining(r).explains); + try std.testing.expectEqualStrings("newName", explaining(r).arg); + try std.testing.expectEqual(Kind.definition, explaining(base).explains); +} + test "LSP encoders report every insufficient output capacity" { const cases = [_]struct { kind: enum { row, span, source_span, edit, put }, expected: []const u8 }{ .{ .kind = .row, .expected = "file:1:3 hi\n" }, diff --git a/src/macos.zig b/src/macos.zig index 9a734bcc..d550e2bd 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -241,169 +241,8 @@ const FileWatches = struct { } }; -test "mac file watch generations own paths, coalesce, and reject stale callbacks" { - var watches: FileWatches = .{}; - defer watches.deinit(std.testing.allocator); - - var first_path = [_]u8{ '/', 't', 'm', 'p', '/', 'a' }; - const first = try watches.replace( - std.testing.allocator, - 3, - &first_path, - 41, - .{ .text = 11 }, - ); - first_path[first_path.len - 1] = 'x'; - try std.testing.expectEqualStrings("/tmp/a", watches.entries[3].?.path); - try std.testing.expect(watches.notify(3, first)); - try std.testing.expect(!watches.notify(3, first)); - try std.testing.expect(watches.takeDirty(3)); - try std.testing.expect(!watches.takeDirty(3)); - - const second = try watches.replace( - std.testing.allocator, - 3, - "/tmp/b", - 42, - .{ .text = 22 }, - ); - try std.testing.expect(second != first); - try std.testing.expect(!watches.notify(3, first)); - try std.testing.expect(watches.notify(3, second)); - try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); - try std.testing.expect(watches.takeDirty(3)); - try std.testing.expect(watches.retry(3, second)); - try std.testing.expect(!watches.retry(3, second)); - try std.testing.expect(watches.takeDirty(3)); - try std.testing.expect(watches.notify(3, second)); - try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); - try std.testing.expect(watches.takeDirty(3)); - watches.restampText(3, "/tmp/not-b", 99); - try std.testing.expectEqual(@as(u64, 22), watches.entries[3].?.generation_on_disk.text); - watches.restampText(3, "/tmp/b", 33); - try std.testing.expectEqual(@as(u64, 33), watches.entries[3].?.generation_on_disk.text); - - const stopped = watches.stop(std.testing.allocator, 3); - try std.testing.expect(stopped != second); - try std.testing.expect(!watches.notify(3, second)); - try std.testing.expect(!watches.retry(3, second)); - try std.testing.expect(watches.entries[3] == null); - - _ = try watches.replace(std.testing.allocator, 4, "/tmp/book.pdf", 77, .{ .kind = null }); - watches.restampText(4, "/tmp/book.pdf", 123); - try std.testing.expect(watches.entries[4].?.generation_on_disk.kind == null); -} - const file_watcher_swift = @embedFile("macos/Sources/FileWatcher.swift"); -test "mac queued results never cancel a newer LSP request" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var st: State = .{ - .gpa = gpa, - .threaded = undefined, - .io = std.testing.io, - .core = core, - .runtime = .{}, - .config_arena = .init(gpa), - .prompt_rcs = .{}, - .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, - }; - defer st.config_arena.deinit(); - defer st.inbox.close(); - core.lspRequest(0, .status, ""); - const old_id = core.lsp_ask.wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_ask.wait.?.id; - st.inbox.lsp_id = current_id; - st.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - // The inbox turns the superseded answer away. - st.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expectEqual(@as(usize, 0), st.inbox.completion_len); - _ = drainInbox(&st); - try std.testing.expect(st.inbox.lsp_task != null); - try std.testing.expectEqual(current_id, st.inbox.lsp_task.?.id); - try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); - st.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); - try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.inbox.lsp_task == null); - try std.testing.expect(core.lsp_ask.wait == null); -} - -test "mac 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 st: State = .{ - .gpa = failing.allocator(), - .threaded = undefined, - .io = failing_io, - .core = core, - .runtime = .{}, - .config_arena = .init(gpa), - .prompt_rcs = .{}, - .inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io }, - }; - defer st.config_arena.deinit(); - defer st.inbox.close(); - 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 = "", - }; - lspRequest(&st, 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; - pipeRequest(&st, pipe_id); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(st.inbox.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); - } -} - -test "mac host watcher covers file and directory vnode events, debounce, and generation callback" { - try std.testing.expect(std.mem.indexOf( - u8, - file_watcher_swift, - "deletingLastPathComponent()", - ) != null); - try std.testing.expect(std.mem.indexOf( - u8, - file_watcher_swift, - "self.reopenFileSource()", - ) != null); - try std.testing.expect(std.mem.indexOf( - u8, - file_watcher_swift, - "DispatchQueue.main.asyncAfter", - ) != null); - try std.testing.expect(std.mem.indexOf( - u8, - file_watcher_swift, - "pardes_watch_changed(self.pane, self.generation)", - ) != null); -} - const Inbox = host_io.Inbox; const Msg = Inbox.Msg; @@ -499,7 +338,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { .boot = .tty, .frame_allocator = allocs.frame, .image_allocator = allocs.image, - + .tree_sitter_allocator = allocs.tree_sitter, }; if (captureEnv(config_arena.allocator())) |*env| { @@ -656,38 +495,6 @@ fn spendTickTime(previous_ns: u64, now_ns: u64, bank_ns: u64) TickSpend { return .{ .elapsed_ns = elapsed, .steps = steps, .bank_ns = bank }; } -test "the animation clock spends real time, not callbacks" { - const frame = pardes.animation.frame_ns; - const expectEqual = std.testing.expectEqual; - - const first = spendTickTime(0, 999 * std.time.ns_per_s, 0); - try expectEqual(@as(u32, 1), first.steps); - try expectEqual(frame, first.elapsed_ns); - - const on_time = spendTickTime(1_000, 1_000 + frame, 0); - try expectEqual(@as(u32, 1), on_time.steps); - try expectEqual(@as(u64, 0), on_time.bank_ns); - - const late = spendTickTime(1_000, 1_000 + 2 * frame, 0); - try expectEqual(@as(u32, 2), late.steps); - - var bank: u64 = 0; - var steps: u32 = 0; - for (0..3) |_| { - const partial = spendTickTime(1_000, 1_000 + 6 * std.time.ns_per_ms, bank); - bank = partial.bank_ns; - steps += partial.steps; - } - try expectEqual(@as(u32, 1), steps); - try expectEqual(@as(u64, 2 * std.time.ns_per_ms), bank); - - const stall = spendTickTime(1_000, 1_000 + 10 * std.time.ns_per_s, 0); - try expectEqual(max_tick_catch_up_ns, stall.elapsed_ns); - try expectEqual(@as(u32, @intCast(max_tick_catch_up_ns / frame)), stall.steps); - - try expectEqual(@as(u32, 1), spendTickTime(5_000, 4_000, 0).steps); -} - export fn pardes_animating() bool { pardes.turn.wake(); defer pardes.turn.rest(); @@ -796,31 +603,6 @@ export fn pardes_fallback_font_name(index: u32, len: *u32) ?[*]const u8 { return name.ptr; } -test "tagline percent falls back before init and follows live core state" { - try std.testing.expectEqual(pardes.config.gui_tagline_font_percent, taglineFontPercent(null)); - - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const changed: u8 = if (pardes.config.gui_tagline_font_percent == 37) 38 else 37; - core.settings.font.tagline_percent = changed; - try std.testing.expectEqual(changed, taglineFontPercent(core)); -} - -test "the fallback preference order crosses the ABI intact and ends at the boundary" { - try std.testing.expectEqual(@as(u32, fonts.fallback_names.len), pardes_fallback_font_count()); - try std.testing.expect(pardes_fallback_font_count() > 0); - - for (fonts.fallback_names, 0..) |want, i| { - var len: u32 = 0; - const got = pardes_fallback_font_name(@intCast(i), &len) orelse return error.MissingFallbackName; - try std.testing.expectEqualStrings(want, got[0..len]); - } - - var len: u32 = 12345; - try std.testing.expect(pardes_fallback_font_name(pardes_fallback_font_count(), &len) == null); - try std.testing.expectEqual(@as(u32, 0), len); -} - export fn pardes_scene() Scene { pardes.turn.wake(); defer pardes.turn.rest(); @@ -1184,166 +966,10 @@ fn restoreCore(st: *State) bool { return true; } -test "mac Restore keeps host state and rejects callbacks from the old core" { - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - var st: State = .{ - .gpa = gpa, - .threaded = undefined, - .io = std.testing.io, - .core = core, - .runtime = .{}, - .config_arena = .init(gpa), - .prompt_rcs = .{}, - .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, - .frame_len = 7, - .rotate_coasting = true, - }; - defer st.core.deinit(); - defer st.config_arena.deinit(); - defer st.file_watches.deinit(gpa); - defer st.inbox.close(); - const marker = try st.config_arena.allocator().dupe(u8, "host configuration"); - _ = try core.setTestFile("saved body\n"); - const old_serial = core.panes[0].?.serial; - st.gens[0] = 23; - const old_watch = try st.file_watches.replace(gpa, 0, "/test.txt", old_serial, .{ .text = 0 }); - try dump.dumpState(core); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "restore.zon", .data = core.dump_out.? }); - while (core.nextEffect()) |_| {} - - var command: [512]u8 = undefined; - core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/missing.zon", .{tmp.sub_path}) }); - try std.testing.expect(!restoreCore(&st)); - try std.testing.expectEqual(core, st.core); - try std.testing.expectEqual(old_watch, st.file_watches.entries[0].?.generation); - try std.testing.expect(st.rotate_coasting); - - core.lspRequest(0, .status, ""); - const old_request = core.lsp_ask.wait.?.id; - st.inbox.lsp_id = old_request; - st.inbox.lsp_task = .{ .id = old_request, .future = .{ .any_future = null, .result = {} } }; - st.inbox.push(.{ .lsp = .{ .id = old_request, .rows = try gpa.dupe(u8, "old result") } }); - for (0..selection_pipe.Tasks.capacity) |index| { - const id: u32 = @intCast(index); - try std.testing.expect(st.pipe_tasks.add(.{ .id = id, .future = .{ .any_future = null, .result = {} } })); - st.inbox.push(.{ .pipe = .{ - .id = id, - .success = false, - .outputs = &.{}, - .failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") }, - } }); - } - st.inbox.acceptReader(0, 23); - _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output")); - core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); - try std.testing.expect(restoreCore(&st)); - try std.testing.expect(st.core != core); - try std.testing.expect(st.core.panes[0].?.serial > old_serial); - try std.testing.expectEqualStrings("saved body\n", st.core.panes[0].?.file.?.content); - try std.testing.expectEqualStrings("host configuration", marker); - try std.testing.expectEqual(@as(usize, 0), st.frame_len); - try std.testing.expect(!st.rotate_coasting); - try std.testing.expectEqual(@as(u32, 24), st.gens[0]); - try std.testing.expect(!st.file_watches.notify(0, old_watch)); - try std.testing.expect(st.file_watches.generations[0] > old_watch); - try std.testing.expectEqual(@as(usize, 0), st.inbox.len); - try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); - try std.testing.expect(st.inbox.lsp_task == null); - try std.testing.expect(!drainInbox(&st)); - try std.testing.expect(!st.cwd_stale[0]); - - st.core.lspRequest(0, .status, ""); - const new_request = st.core.lsp_ask.wait.?.id; - try std.testing.expect(new_request > old_request); - st.inbox.lsp_id = new_request; - st.inbox.lsp_task = .{ .id = new_request, .future = .{ .any_future = null, .result = {} } }; - st.inbox.push(.{ .lsp = .{ .id = new_request, .rows = &.{} } }); - try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.inbox.lsp_task == null); - try std.testing.expect(st.core.lsp_ask.wait == null); - - const pane = st.core.panes[0].?; - pane.body.cur_col = 4; - pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - st.core.update(.{ .key = .{ .cp = '|' } }); - st.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - st.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = st.core.pipe.wait.?.id; - try std.testing.expect(st.pipe_tasks.add(.{ .id = pipe_id, .future = .{ .any_future = null, .result = {} } })); - const output = try gpa.dupe(u8, "FRESH"); - const outputs = gpa.dupe([]u8, &.{output}) catch |err| { - gpa.free(output); - return err; - }; - st.inbox.push(.{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); - try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.core.pipe.wait == null); - try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); - try std.testing.expectEqualStrings("FRESH body\n", pane.file.?.content); -} - -test "mac Restore cancels a PTY reader waiting for output capacity" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var st: State = .{ - .gpa = gpa, - .threaded = undefined, - .io = io, - .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }), - .runtime = .{}, - .config_arena = .init(gpa), - .prompt_rcs = .{}, - .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io }, - }; - defer st.core.deinit(); - defer st.config_arena.deinit(); - defer st.file_watches.deinit(gpa); - defer st.inbox.close(); - try dump.dumpState(st.core); - try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? }); - while (st.core.nextEffect()) |_| {} - st.inbox.acceptReader(1, 1); - for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output")); - const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40); - st.gens[0] = 1; - st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } }; - defer { - if (st.ptys[0]) |pt| if (pt.pid == child.pid) reap(&st, 0); - if (libc.waitpid(child.pid, null, posix.W.NOHANG) == 0) { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - } - } - startReader(&st, &st.ptys[0].?, 0); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); - for (0..1000) |_| { - if (st.inbox.space.state.load(.acquire).waiters != 0) break; - try io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expectEqual(@as(u16, 1), st.inbox.space.state.load(.acquire).waiters); - var command: [512]u8 = undefined; - st.core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); - try std.testing.expect(restoreCore(&st)); - try std.testing.expect(st.ptys[0] == null); - try std.testing.expectEqual(@as(usize, 0), st.inbox.len); - try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters); - st.inbox.acceptReader(0, st.gens[0]); - _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output")); - var batch = st.inbox.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("fresh output", batch.items[0].output.bytes); -} - -export fn pardes_animation_tick() bool { - pardes.turn.wake(); - defer pardes.turn.rest(); - const st = &(state orelse return false); +export fn pardes_animation_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); const now: u64 = @intCast(std.Io.Clock.awake.now(st.io).nanoseconds); const spend = spendTickTime(st.last_tick_ns, now, st.tick_bank_ns); @@ -2471,6 +2097,380 @@ fn expectSameAbi(comptime C: type, comptime Z: type) !void { try std.testing.expectEqual(@sizeOf(c_fn.return_type.?), @sizeOf(z_fn.return_type.?)); } +test "mac file watch generations own paths, coalesce, and reject stale callbacks" { + var watches: FileWatches = .{}; + defer watches.deinit(std.testing.allocator); + + var first_path = [_]u8{ '/', 't', 'm', 'p', '/', 'a' }; + const first = try watches.replace( + std.testing.allocator, + 3, + &first_path, + 41, + .{ .text = 11 }, + ); + first_path[first_path.len - 1] = 'x'; + try std.testing.expectEqualStrings("/tmp/a", watches.entries[3].?.path); + try std.testing.expect(watches.notify(3, first)); + try std.testing.expect(!watches.notify(3, first)); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(!watches.takeDirty(3)); + + const second = try watches.replace( + std.testing.allocator, + 3, + "/tmp/b", + 42, + .{ .text = 22 }, + ); + try std.testing.expect(second != first); + try std.testing.expect(!watches.notify(3, first)); + try std.testing.expect(watches.notify(3, second)); + try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(watches.retry(3, second)); + try std.testing.expect(!watches.retry(3, second)); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(watches.notify(3, second)); + try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); + try std.testing.expect(watches.takeDirty(3)); + watches.restampText(3, "/tmp/not-b", 99); + try std.testing.expectEqual(@as(u64, 22), watches.entries[3].?.generation_on_disk.text); + watches.restampText(3, "/tmp/b", 33); + try std.testing.expectEqual(@as(u64, 33), watches.entries[3].?.generation_on_disk.text); + + const stopped = watches.stop(std.testing.allocator, 3); + try std.testing.expect(stopped != second); + try std.testing.expect(!watches.notify(3, second)); + try std.testing.expect(!watches.retry(3, second)); + try std.testing.expect(watches.entries[3] == null); + + _ = try watches.replace(std.testing.allocator, 4, "/tmp/book.pdf", 77, .{ .kind = null }); + watches.restampText(4, "/tmp/book.pdf", 123); + try std.testing.expect(watches.entries[4].?.generation_on_disk.kind == null); +} + +test "mac queued results never cancel a newer LSP request" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = std.testing.io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, + }; + defer st.config_arena.deinit(); + defer st.inbox.close(); + core.lspRequest(0, .status, ""); + const old_id = core.lsp_ask.wait.?.id; + core.lspRequest(0, .status, ""); + const current_id = core.lsp_ask.wait.?.id; + st.inbox.lsp_id = current_id; + st.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + // The inbox turns the superseded answer away. + st.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); + try std.testing.expectEqual(@as(usize, 0), st.inbox.completion_len); + _ = drainInbox(&st); + try std.testing.expect(st.inbox.lsp_task != null); + try std.testing.expectEqual(current_id, st.inbox.lsp_task.?.id); + try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); + st.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(core.lsp_ask.wait == null); +} + +test "mac 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 st: State = .{ + .gpa = failing.allocator(), + .threaded = undefined, + .io = failing_io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io }, + }; + defer st.config_arena.deinit(); + defer st.inbox.close(); + 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 = "", + }; + lspRequest(&st, 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; + pipeRequest(&st, pipe_id); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + } +} + +test "mac host watcher covers file and directory vnode events, debounce, and generation callback" { + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "deletingLastPathComponent()", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "self.reopenFileSource()", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "DispatchQueue.main.asyncAfter", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "pardes_watch_changed(self.pane, self.generation)", + ) != null); +} + +test "the animation clock spends real time, not callbacks" { + const frame = pardes.animation.frame_ns; + const expectEqual = std.testing.expectEqual; + + const first = spendTickTime(0, 999 * std.time.ns_per_s, 0); + try expectEqual(@as(u32, 1), first.steps); + try expectEqual(frame, first.elapsed_ns); + + const on_time = spendTickTime(1_000, 1_000 + frame, 0); + try expectEqual(@as(u32, 1), on_time.steps); + try expectEqual(@as(u64, 0), on_time.bank_ns); + + const late = spendTickTime(1_000, 1_000 + 2 * frame, 0); + try expectEqual(@as(u32, 2), late.steps); + + var bank: u64 = 0; + var steps: u32 = 0; + for (0..3) |_| { + const partial = spendTickTime(1_000, 1_000 + 6 * std.time.ns_per_ms, bank); + bank = partial.bank_ns; + steps += partial.steps; + } + try expectEqual(@as(u32, 1), steps); + try expectEqual(@as(u64, 2 * std.time.ns_per_ms), bank); + + const stall = spendTickTime(1_000, 1_000 + 10 * std.time.ns_per_s, 0); + try expectEqual(max_tick_catch_up_ns, stall.elapsed_ns); + try expectEqual(@as(u32, @intCast(max_tick_catch_up_ns / frame)), stall.steps); + + try expectEqual(@as(u32, 1), spendTickTime(5_000, 4_000, 0).steps); +} + +test "tagline percent falls back before init and follows live core state" { + try std.testing.expectEqual(pardes.config.gui_tagline_font_percent, taglineFontPercent(null)); + + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const changed: u8 = if (pardes.config.gui_tagline_font_percent == 37) 38 else 37; + core.settings.font.tagline_percent = changed; + try std.testing.expectEqual(changed, taglineFontPercent(core)); +} + +test "the fallback preference order crosses the ABI intact and ends at the boundary" { + try std.testing.expectEqual(@as(u32, fonts.fallback_names.len), pardes_fallback_font_count()); + try std.testing.expect(pardes_fallback_font_count() > 0); + + for (fonts.fallback_names, 0..) |want, i| { + var len: u32 = 0; + const got = pardes_fallback_font_name(@intCast(i), &len) orelse return error.MissingFallbackName; + try std.testing.expectEqualStrings(want, got[0..len]); + } + + var len: u32 = 12345; + try std.testing.expect(pardes_fallback_font_name(pardes_fallback_font_count(), &len) == null); + try std.testing.expectEqual(@as(u32, 0), len); +} + +test "mac Restore keeps host state and rejects callbacks from the old core" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = std.testing.io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, + .frame_len = 7, + .rotate_coasting = true, + }; + defer st.core.deinit(); + defer st.config_arena.deinit(); + defer st.file_watches.deinit(gpa); + defer st.inbox.close(); + const marker = try st.config_arena.allocator().dupe(u8, "host configuration"); + _ = try core.setTestFile("saved body\n"); + const old_serial = core.panes[0].?.serial; + st.gens[0] = 23; + const old_watch = try st.file_watches.replace(gpa, 0, "/test.txt", old_serial, .{ .text = 0 }); + try dump.dumpState(core); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "restore.zon", .data = core.dump_out.? }); + while (core.nextEffect()) |_| {} + + var command: [512]u8 = undefined; + core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/missing.zon", .{tmp.sub_path}) }); + try std.testing.expect(!restoreCore(&st)); + try std.testing.expectEqual(core, st.core); + try std.testing.expectEqual(old_watch, st.file_watches.entries[0].?.generation); + try std.testing.expect(st.rotate_coasting); + + core.lspRequest(0, .status, ""); + const old_request = core.lsp_ask.wait.?.id; + st.inbox.lsp_id = old_request; + st.inbox.lsp_task = .{ .id = old_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = old_request, .rows = try gpa.dupe(u8, "old result") } }); + for (0..selection_pipe.Tasks.capacity) |index| { + const id: u32 = @intCast(index); + try std.testing.expect(st.pipe_tasks.add(.{ .id = id, .future = .{ .any_future = null, .result = {} } })); + st.inbox.push(.{ .pipe = .{ + .id = id, + .success = false, + .outputs = &.{}, + .failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") }, + } }); + } + st.inbox.acceptReader(0, 23); + _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output")); + core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); + try std.testing.expect(restoreCore(&st)); + try std.testing.expect(st.core != core); + try std.testing.expect(st.core.panes[0].?.serial > old_serial); + try std.testing.expectEqualStrings("saved body\n", st.core.panes[0].?.file.?.content); + try std.testing.expectEqualStrings("host configuration", marker); + try std.testing.expectEqual(@as(usize, 0), st.frame_len); + try std.testing.expect(!st.rotate_coasting); + try std.testing.expectEqual(@as(u32, 24), st.gens[0]); + try std.testing.expect(!st.file_watches.notify(0, old_watch)); + try std.testing.expect(st.file_watches.generations[0] > old_watch); + try std.testing.expectEqual(@as(usize, 0), st.inbox.len); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(!drainInbox(&st)); + try std.testing.expect(!st.cwd_stale[0]); + + st.core.lspRequest(0, .status, ""); + const new_request = st.core.lsp_ask.wait.?.id; + try std.testing.expect(new_request > old_request); + st.inbox.lsp_id = new_request; + st.inbox.lsp_task = .{ .id = new_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = new_request, .rows = &.{} } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(st.core.lsp_ask.wait == null); + + const pane = st.core.panes[0].?; + pane.body.cur_col = 4; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + st.core.update(.{ .key = .{ .cp = '|' } }); + st.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + st.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = st.core.pipe.wait.?.id; + try std.testing.expect(st.pipe_tasks.add(.{ .id = pipe_id, .future = .{ .any_future = null, .result = {} } })); + const output = try gpa.dupe(u8, "FRESH"); + const outputs = gpa.dupe([]u8, &.{output}) catch |err| { + gpa.free(output); + return err; + }; + st.inbox.push(.{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.core.pipe.wait == null); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + try std.testing.expectEqualStrings("FRESH body\n", pane.file.?.content); +} + +test "mac Restore cancels a PTY reader waiting for output capacity" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = io, + .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }), + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io }, + }; + defer st.core.deinit(); + defer st.config_arena.deinit(); + defer st.file_watches.deinit(gpa); + defer st.inbox.close(); + try dump.dumpState(st.core); + try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? }); + while (st.core.nextEffect()) |_| {} + st.inbox.acceptReader(1, 1); + for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output")); + const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40); + st.gens[0] = 1; + st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } }; + defer { + if (st.ptys[0]) |pt| if (pt.pid == child.pid) reap(&st, 0); + if (libc.waitpid(child.pid, null, posix.W.NOHANG) == 0) { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + } + } + startReader(&st, &st.ptys[0].?, 0); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); + for (0..1000) |_| { + if (st.inbox.space.state.load(.acquire).waiters != 0) break; + try io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expectEqual(@as(u16, 1), st.inbox.space.state.load(.acquire).waiters); + var command: [512]u8 = undefined; + st.core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); + try std.testing.expect(restoreCore(&st)); + try std.testing.expect(st.ptys[0] == null); + try std.testing.expectEqual(@as(usize, 0), st.inbox.len); + try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters); + st.inbox.acceptReader(0, st.gens[0]); + _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output")); + var batch = st.inbox.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("fresh output", batch.items[0].output.bytes); +} + test "pardes.h declares every export the way it is defined" { const c = @import("pardes.h"); try expectSameAbi(@TypeOf(c.pardes_init), @TypeOf(pardes_init)); @@ -2855,4 +2855,3 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { try std.testing.expectEqual(@as(u8, 'G'), canonical[18].text[0]); try std.testing.expectEqual(encodeCell(.{}).len, canonical[10].len); } - diff --git a/src/main.zig b/src/main.zig index c36c4eb7..c7f1f960 100644 --- a/src/main.zig +++ b/src/main.zig @@ -286,15 +286,6 @@ fn hasPane(index: []const u8, serial: u32) bool { return false; } -test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { - const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; - try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); - try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); - try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); - try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); - try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); -} - fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { die(io, fmt ++ "\nTry 'pardes --help'.", args); } @@ -349,18 +340,6 @@ fn libcResult(rc: usize) c_int { return -1; } -test "tcgetattr writes nothing past a Zig termios" { - if (comptime !(builtin.os.tag == .linux and builtin.abi.isGnu())) return error.SkipZigTest; - const master = std.c.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(std.c.mode_t, 0)); - if (master < 0) return error.SkipZigTest; - defer _ = std.c.close(master); - var s: extern struct { t: std.c.termios, canary: [32]u8 } = .{ .t = undefined, .canary = @splat(0xAA) }; - try std.testing.expectEqual(0, std.c.tcgetattr(master, &s.t)); - try std.testing.expectEqualSlices(u8, &@as([32]u8, @splat(0xAA)), &s.canary); - try std.testing.expectEqual(0, std.c.tcsetattr(master, .NOW, &s.t)); - try std.testing.expectEqual(-1, std.c.tcgetattr(-1, &s.t)); -} - // init.gpa, what the tui, gui and detached shells allocate from, is their // own fixed arena (memory.host) in a release build, spilling to libc's // malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start @@ -1072,6 +1051,38 @@ fn parseCtrlKey(raw: []const u8) ?u21 { return c; } +/// Where Recent's file (0.24) and the store before it were kept: +/// $XDG_STATE_HOME/pardes, else ~/.local/state/pardes. A state file that +/// holds no Recent yet reads them once (Db.zig). +fn oldRecentDir(arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { + if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.Io.Dir.path.isAbsolute(base)) + return std.Io.Dir.path.join(arena, &.{ base, "pardes" }) catch null; + const home = env.get("HOME") orelse return null; + if (home.len == 0) return null; + return std.Io.Dir.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch null; +} + +test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { + const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; + try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); + try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); + try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); + try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); + try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); +} + +test "tcgetattr writes nothing past a Zig termios" { + if (comptime !(builtin.os.tag == .linux and builtin.abi.isGnu())) return error.SkipZigTest; + const master = std.c.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(std.c.mode_t, 0)); + if (master < 0) return error.SkipZigTest; + defer _ = std.c.close(master); + var s: extern struct { t: std.c.termios, canary: [32]u8 } = .{ .t = undefined, .canary = @splat(0xAA) }; + try std.testing.expectEqual(0, std.c.tcgetattr(master, &s.t)); + try std.testing.expectEqualSlices(u8, &@as([32]u8, @splat(0xAA)), &s.canary); + try std.testing.expectEqual(0, std.c.tcsetattr(master, .NOW, &s.t)); + try std.testing.expectEqual(-1, std.c.tcgetattr(-1, &s.t)); +} + test { _ = pardes.config.User; _ = @import("crash.zig"); @@ -1096,14 +1107,3 @@ test { if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig"); if (comptime pardes.font_picker) _ = @import("fonts.zig"); } - -/// Where Recent's file (0.24) and the store before it were kept: -/// $XDG_STATE_HOME/pardes, else ~/.local/state/pardes. A state file that -/// holds no Recent yet reads them once (Db.zig). -fn oldRecentDir(arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { - if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.Io.Dir.path.isAbsolute(base)) - return std.Io.Dir.path.join(arena, &.{ base, "pardes" }) catch null; - const home = env.get("HOME") orelse return null; - if (home.len == 0) return null; - return std.Io.Dir.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch null; -} diff --git a/src/modal.zig b/src/modal.zig index 89046820..6f0bdc9c 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -166,9 +166,9 @@ pub const Normal = struct { }; /// The roles from `from` to `to`, in the order a context tries them. - fn roles(comptime from: Role, comptime to: Role) [@intFromEnum(to) - @intFromEnum(from) + 1]Role { - var out: [@intFromEnum(to) - @intFromEnum(from) + 1]Role = undefined; - for (&out, @intFromEnum(from)..) |*role, i| role.* = @enumFromInt(i); + fn roles(comptime from: Role, comptime to: Role) [@backingInt(to) - @backingInt(from) + 1]Role { + var out: [@backingInt(to) - @backingInt(from) + 1]Role = undefined; + for (&out, @backingInt(from)..) |*role, i| role.* = @fromBackingInt(@intCast(i)); return out; } const goto_roles: []const Role = &roles(.goto_file_start, .goto_callstack); @@ -500,10 +500,6 @@ pub const Normal = struct { } }; -test { - _ = Normal; -} - // Cursor columns are UTF-8 byte offsets at grapheme boundaries; line.len is the terminator. pub const Cursor = struct { @@ -729,38 +725,6 @@ pub fn lineStartOffset(content: []const u8, row: usize) usize { return content.len; } -test "lineStartOffset by blocks and offsetAt agree with a line at a time" { - var prng: std.Random.DefaultPrng = .init(0x9e3779b9); - const random = prng.random(); - var buf: [300]u8 = undefined; - for (0..2000) |_| { - const len = random.uintLessThan(usize, buf.len); - for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 4) == 0) '\n' else 'a'; - const text = buf[0..len]; - for (0..len + 3) |row| { - var off: usize = 0; - var r: usize = 0; - const want = while (r < row) : (r += 1) { - off = (std.mem.indexOfScalarPos(u8, text, off, '\n') orelse break text.len) + 1; - } else off; - try std.testing.expectEqual(want, lineStartOffset(text, row)); - const cursor: Cursor = .{ .row = row, .col = random.uintLessThan(usize, 6) }; - const clamped = lineStartOffset(text, @min(row, cursorLineCount(text) - 1)); - const end = std.mem.indexOfScalarPos(u8, text, clamped, '\n') orelse text.len; - try std.testing.expectEqual(clamped + graphemeStart(text[clamped..end], @min(cursor.col, end - clamped)), offsetAt(text, cursor)); - // lineSpan, as it was: a line at a time, null past the last. - const span: ?LineSpan = span: { - if (text.len == 0) break :span null; - var start: usize = 0; - for (0..row) |_| start = (std.mem.indexOfScalarPos(u8, text, start, '\n') orelse break :span null) + 1; - if (start == text.len and !(row == 0 or text[text.len - 1] == '\n')) break :span null; - break :span .{ .start = start, .end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len }; - }; - try std.testing.expectEqual(span, lineSpan(text, row)); - } - } -} - // the text of line `row` (no terminator), a slice into `content`. pub fn lineSlice(content: []const u8, row: usize) []const u8 { const start = lineStartOffset(content, row); @@ -1401,23 +1365,6 @@ pub fn selectParagraph(text: []const u8, r: Selection, around: bool, count: usiz }; } -test "selection textobjects distinguish words and paragraph boundaries" { - const t = "alpha beta gamma\n"; - // miw mid-word - var r = selectWord(t, .{ .anchor = 8, .head = 9 }, false, false); - try std.testing.expectEqual(@as(usize, 6), r.anchor); - try std.testing.expectEqual(@as(usize, 10), r.head); - // maw on the space after "beta": collapses to the boundary - r = selectWord(t, .{ .anchor = 10, .head = 11 }, true, false); - try std.testing.expectEqual(@as(usize, 10), r.anchor); - try std.testing.expectEqual(@as(usize, 10), r.head); - const t2 = "aa\n\ncc\n"; - // mip from the blank line selects the NEXT paragraph - r = selectParagraph(t2, .{ .anchor = 3, .head = 4 }, false, 1); - try std.testing.expectEqual(@as(usize, 4), r.anchor); - try std.testing.expectEqual(@as(usize, 7), r.head); -} - /// A line's indent as it is, tabs and spaces both, as acme's autoindent /// copies it: what o/O/insert-newline give the new line. pub fn indentText(line: []const u8) []const u8 { @@ -1434,14 +1381,6 @@ pub fn newlineIndentWidth(line: []const u8, col: usize) usize { return indentText(line).len + @as(usize, if (extra) INDENT_W else 0); } -test "newline indent keeps levels and adds one after delimiters" { - try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth(" value", 9)); - try std.testing.expectEqual(@as(usize, 8), newlineIndentWidth(" call()", 10)); - try std.testing.expectEqual(@as(usize, 8), newlineIndentWidth(" callback({}) ", 16)); - try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth("work(", 5)); - try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth("list[tail", 5)); -} - /// Increment a selected decimal integer, preserving zero-padding across sign changes. pub fn incrementDecimal(alloc: std.mem.Allocator, frag: []const u8, amount: i64) !?[]u8 { if (frag.len == 0) return null; @@ -1475,6 +1414,67 @@ pub fn incrementDecimal(alloc: std.mem.Allocator, frag: []const u8, amount: i64) return out; } +test { + _ = Normal; +} + +test "lineStartOffset by blocks and offsetAt agree with a line at a time" { + var prng: std.Random.DefaultPrng = .init(0x9e3779b9); + const random = prng.random(); + var buf: [300]u8 = undefined; + for (0..2000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 4) == 0) '\n' else 'a'; + const text = buf[0..len]; + for (0..len + 3) |row| { + var off: usize = 0; + var r: usize = 0; + const want = while (r < row) : (r += 1) { + off = (std.mem.indexOfScalarPos(u8, text, off, '\n') orelse break text.len) + 1; + } else off; + try std.testing.expectEqual(want, lineStartOffset(text, row)); + const cursor: Cursor = .{ .row = row, .col = random.uintLessThan(usize, 6) }; + const clamped = lineStartOffset(text, @min(row, cursorLineCount(text) - 1)); + const end = std.mem.indexOfScalarPos(u8, text, clamped, '\n') orelse text.len; + try std.testing.expectEqual(clamped + graphemeStart(text[clamped..end], @min(cursor.col, end - clamped)), offsetAt(text, cursor)); + // lineSpan, as it was: a line at a time, null past the last. + const span: ?LineSpan = span: { + if (text.len == 0) break :span null; + var start: usize = 0; + for (0..row) |_| start = (std.mem.indexOfScalarPos(u8, text, start, '\n') orelse break :span null) + 1; + if (start == text.len and !(row == 0 or text[text.len - 1] == '\n')) break :span null; + break :span .{ .start = start, .end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len }; + }; + try std.testing.expectEqual(span, lineSpan(text, row)); + } + } +} + +test "selection textobjects distinguish words and paragraph boundaries" { + const t = "alpha beta gamma\n"; + // miw mid-word + var r = selectWord(t, .{ .anchor = 8, .head = 9 }, false, false); + try std.testing.expectEqual(@as(usize, 6), r.anchor); + try std.testing.expectEqual(@as(usize, 10), r.head); + // maw on the space after "beta": collapses to the boundary + r = selectWord(t, .{ .anchor = 10, .head = 11 }, true, false); + try std.testing.expectEqual(@as(usize, 10), r.anchor); + try std.testing.expectEqual(@as(usize, 10), r.head); + const t2 = "aa\n\ncc\n"; + // mip from the blank line selects the NEXT paragraph + r = selectParagraph(t2, .{ .anchor = 3, .head = 4 }, false, 1); + try std.testing.expectEqual(@as(usize, 4), r.anchor); + try std.testing.expectEqual(@as(usize, 7), r.head); +} + +test "newline indent keeps levels and adds one after delimiters" { + try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth(" value", 9)); + try std.testing.expectEqual(@as(usize, 8), newlineIndentWidth(" call()", 10)); + try std.testing.expectEqual(@as(usize, 8), newlineIndentWidth(" callback({}) ", 16)); + try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth("work(", 5)); + try std.testing.expectEqual(@as(usize, 4), newlineIndentWidth("list[tail", 5)); +} + test "word selections match Helix motions" { const t = "alpha beta\n"; // w from a fresh 1-wide cursor selects "alpha " (cursor on the space) diff --git a/src/mouse.zig b/src/mouse.zig index 4c909104..d15616b5 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -162,64 +162,6 @@ fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { return r.y + r.h -| 1; } -fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { - const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); - p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); - p.view().active = p.view().cols[1].panes[0]; - p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell below it, same column - p.sync(); - return p; -} - -test "a pane's last row of text is no resize handle; the rule over the next pane is" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const seam = seamRowOf(p, 1, 0); - const inside = p.view().col_x[1] + p.view().col_w[1] / 2; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = seam } }); - try std.testing.expect(p.view().drag != .border_h); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = seam } }); - try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); -} - -test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const upper = p.view().cols[1].panes[0]; - const lower = p.view().cols[1].panes[1]; - const grip_x = p.view().rects[lower].x; - // Up, past the pane above's first row: a text pane keeps its tag, a - // terminal its tag and two rows (layout.floorRows). - const top = p.view().rects[upper].y; - const above = p.panes[upper].?; - const floor: u16 = if (above.isTerminal()) above.tag_rows + layout.min_body_rows else 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = top } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = top } }); - p.sync(); - try std.testing.expectEqual(floor, p.view().rects[upper].h); - try std.testing.expectEqual(lower, p.view().cols[1].panes[1]); - // Down, inside itself: its top follows, the pane above taking the rows. - const to = p.view().rects[lower].y + 6; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = to } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = to } }); - p.sync(); - try std.testing.expectEqual(to, p.view().rects[lower].y); -} - -fn nudgeRightSeam(p: *Pardes, delta: i32) u16 { - const from = seamRowOf(p, 1, 0); - const inside = p.view().col_x[1] + p.view().col_w[1] / 2; - const to: u16 = @intCast(@as(i32, from) + delta); - // On the rule a pixel frontend draws over the lower pane's first row. - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = from + 1, .rule_above = true } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = inside, .row = to + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = to + 1 } }); - p.sync(); - return seamRowOf(p, 1, 0); -} - pub const ChromeTarget = struct { col: u16, row: u16 }; /// The chrome a press at `col`, `row` takes: the tag rows; then, @@ -252,26 +194,6 @@ pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { return null; } -test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - // Column 0's two panes share its rows evenly; column 1's lower one is - // tall, its middle a body row. - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const seam = seamRowOf(p, 0, 0); - const mid = p.view().col_x[0] + p.view().col_w[0] / 2; - const top = p.view().rects[p.view().cols[0].panes[0]].y; - const low = p.view().rects[p.view().cols[1].panes[1]]; - const body = low.y + low.h / 2; - try std.testing.expectEqual(ChromeTarget{ .col = 5, .row = 0 }, chromeTarget(p, 5, 0).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle + 1, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam - 1).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = top }, chromeTarget(p, mid, top).?); - try std.testing.expect(chromeTarget(p, mid, seam - 3) == null); -} - pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { for (p.panes, 0..) |slot, id| { if (slot == null) continue; @@ -1467,6 +1389,136 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); } +const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; + +fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + p.view().active = p.view().cols[1].panes[0]; + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell below it, same column + p.sync(); + return p; +} + +fn nudgeRightSeam(p: *Pardes, delta: i32) u16 { + const from = seamRowOf(p, 1, 0); + const inside = p.view().col_x[1] + p.view().col_w[1] / 2; + const to: u16 = @intCast(@as(i32, from) + delta); + // On the rule a pixel frontend draws over the lower pane's first row. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = from + 1, .rule_above = true } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = inside, .row = to + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = to + 1 } }); + p.sync(); + return seamRowOf(p, 1, 0); +} + +/// A session and a replica joined to it from its dump: digest for digest +/// the same, and only the session has drawn a frame (its surface is its +/// own, `.local`). What a step does with one input must not depend on that. +fn sessionAndReplica(gpa: std.mem.Allocator, opts: pardes.Options) !struct { a: *Pardes, b: *Pardes } { + const a = try Pardes.init(gpa, opts); + errdefer a.deinit(); + a.update(.{ .resize = .{ .cols = opts.cols, .rows = opts.rows, .row_metrics = test_metrics } }); + a.sync(); + const bytes = try pardes.dump.dumpBytes(a); + defer gpa.free(bytes); + const b = try pardes.dump.load(gpa, a.opts, bytes, null); + errdefer b.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try a.render(frame.allocator()); + try expectSame(a, b, "before the press"); + return .{ .a = a, .b = b }; +} + +/// The two cores' digests equal, else the fields (and pane fields) that differ. +fn expectSame(a: *const Pardes, b: *const Pardes, when: []const u8) !void { + if (pardes.walk.digest(Pardes, a) == pardes.walk.digest(Pardes, b)) return; + const names = comptime pardes.walk.fieldNames(Pardes); + var da: [names.len]u64 = undefined; + var db: [names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(Pardes, a, &da); + _ = pardes.walk.fieldDigests(Pardes, b, &db); + for (names, da, db) |name, x, y| if (x != y) std.debug.print("{s}: {s} differs\n", .{ when, name }); + const pane_names = comptime pardes.walk.fieldNames(pardes.Pane); + for (a.panes, b.panes, 0..) |pa, pb, id| { + const x = pa orelse continue; + const y = pb orelse continue; + var pda: [pane_names.len]u64 = undefined; + var pdb: [pane_names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(pardes.Pane, x, &pda); + _ = pardes.walk.fieldDigests(pardes.Pane, y, &pdb); + for (pane_names, pda, pdb) |name, u, v| if (u != v) std.debug.print("{s}: pane {d}.{s} differs\n", .{ when, id, name }); + } + return error.DigestsDiffer; +} + +fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { + const w: f32 = if (tag) test_metrics.tagline_w else test_metrics.body_w; + const h: f32 = if (tag) test_metrics.tagline_h else test_metrics.body_h; + return .{ + @as(f32, @floatFromInt(layer.viewport.x)) * test_metrics.body_w + (@as(f32, @floatFromInt(col)) + 0.5) * w, + @as(f32, @floatFromInt(layer.viewport.y)) * test_metrics.body_h + 0.5 * h, + }; +} + +test "a pane's last row of text is no resize handle; the rule over the next pane is" { + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + const seam = seamRowOf(p, 1, 0); + const inside = p.view().col_x[1] + p.view().col_w[1] / 2; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = seam } }); + try std.testing.expect(p.view().drag != .border_h); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = seam } }); + try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); +} + +test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + const upper = p.view().cols[1].panes[0]; + const lower = p.view().cols[1].panes[1]; + const grip_x = p.view().rects[lower].x; + // Up, past the pane above's first row: a text pane keeps its tag, a + // terminal its tag and two rows (layout.floorRows). + const top = p.view().rects[upper].y; + const above = p.panes[upper].?; + const floor: u16 = if (above.isTerminal()) above.tag_rows + layout.min_body_rows else 1; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = top } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = top } }); + p.sync(); + try std.testing.expectEqual(floor, p.view().rects[upper].h); + try std.testing.expectEqual(lower, p.view().cols[1].panes[1]); + // Down, inside itself: its top follows, the pane above taking the rows. + const to = p.view().rects[lower].y + 6; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = to } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = to } }); + p.sync(); + try std.testing.expectEqual(to, p.view().rects[lower].y); +} + +test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + // Column 0's two panes share its rows evenly; column 1's lower one is + // tall, its middle a body row. + const handle = p.view().col_x[0] + p.view().col_w[0] - 1; + const seam = seamRowOf(p, 0, 0); + const mid = p.view().col_x[0] + p.view().col_w[0] / 2; + const top = p.view().rects[p.view().cols[0].panes[0]].y; + const low = p.view().rects[p.view().cols[1].panes[1]]; + const body = low.y + low.h / 2; + try std.testing.expectEqual(ChromeTarget{ .col = 5, .row = 0 }, chromeTarget(p, 5, 0).?); + try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle, body).?); + try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle + 1, body).?); + try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam).?); + try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam - 1).?); + try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = top }, chromeTarget(p, mid, top).?); + try std.testing.expect(chromeTarget(p, mid, seam - 3) == null); +} + test "plain left click clears explicit modal selection" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 40, .rows = 10 }); @@ -1915,58 +1967,6 @@ test "a program tracking the mouse gets its clicks, drags and moves over its gri try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); } -const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; - -/// A session and a replica joined to it from its dump: digest for digest -/// the same, and only the session has drawn a frame (its surface is its -/// own, `.local`). What a step does with one input must not depend on that. -fn sessionAndReplica(gpa: std.mem.Allocator, opts: pardes.Options) !struct { a: *Pardes, b: *Pardes } { - const a = try Pardes.init(gpa, opts); - errdefer a.deinit(); - a.update(.{ .resize = .{ .cols = opts.cols, .rows = opts.rows, .row_metrics = test_metrics } }); - a.sync(); - const bytes = try pardes.dump.dumpBytes(a); - defer gpa.free(bytes); - const b = try pardes.dump.load(gpa, a.opts, bytes, null); - errdefer b.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try a.render(frame.allocator()); - try expectSame(a, b, "before the press"); - return .{ .a = a, .b = b }; -} - -/// The two cores' digests equal, else the fields (and pane fields) that differ. -fn expectSame(a: *const Pardes, b: *const Pardes, when: []const u8) !void { - if (pardes.walk.digest(Pardes, a) == pardes.walk.digest(Pardes, b)) return; - const names = comptime pardes.walk.fieldNames(Pardes); - var da: [names.len]u64 = undefined; - var db: [names.len]u64 = undefined; - _ = pardes.walk.fieldDigests(Pardes, a, &da); - _ = pardes.walk.fieldDigests(Pardes, b, &db); - for (names, da, db) |name, x, y| if (x != y) std.debug.print("{s}: {s} differs\n", .{ when, name }); - const pane_names = comptime pardes.walk.fieldNames(pardes.Pane); - for (a.panes, b.panes, 0..) |pa, pb, id| { - const x = pa orelse continue; - const y = pb orelse continue; - var pda: [pane_names.len]u64 = undefined; - var pdb: [pane_names.len]u64 = undefined; - _ = pardes.walk.fieldDigests(pardes.Pane, x, &pda); - _ = pardes.walk.fieldDigests(pardes.Pane, y, &pdb); - for (pane_names, pda, pdb) |name, u, v| if (u != v) std.debug.print("{s}: pane {d}.{s} differs\n", .{ when, id, name }); - } - return error.DigestsDiffer; -} - -fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { - const w: f32 = if (tag) test_metrics.tagline_w else test_metrics.body_w; - const h: f32 = if (tag) test_metrics.tagline_h else test_metrics.body_h; - return .{ - @as(f32, @floatFromInt(layer.viewport.x)) * test_metrics.body_w + (@as(f32, @floatFromInt(col)) + 0.5) * w, - @as(f32, @floatFromInt(layer.viewport.y)) * test_metrics.body_h + 0.5 * h, - }; -} - // A frontend's pointer hit is its own frame's: a step resolves it on the // place the hit carries (Layer.Place), never on this process's last frame // (`surface`, `.local`), so a session and its replica take one input alike diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index 7eb08ba9..5218b937 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -36,7 +36,7 @@ pub fn writeLayout(p: *Pardes, w: *std.Io.Writer) std.Io.Writer.Error!void { const active = activeColumn(p); for (0..p.view().ncol) |c| { try w.print("{d} {d} {d} {d} {s} {s}", .{ - layout.columnSerial(p, c), c, v.col_x[c], v.col_w[c], + layout.columnSerial(p, c), c, v.col_x[c], v.col_w[c], if (active == c) "current" else "notcurrent", if (v.cols[c].n == 0) "empty" else "full", }); for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (p.panes[id]) |pane| try w.print(" {d}", .{pane.serial}); @@ -212,6 +212,38 @@ pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } +/// Whether `line` names a builtin that acts on a pane (every one of pane +/// scope, Edit too, which the root's ctl takes at the active pane) and is +/// not one of `own`, the words its tag holds by default: those a tag no +/// pane owns refuses, never doing them at the pane with the keyboard. +fn paneWord(line: []const u8, own: []const u8) bool { + const cmd = pardes.exec.commandText(line); + const word = cmd[0 .. std.mem.indexOfAny(u8, cmd, " \t+") orelse cmd.len]; + const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), word) orelse return false; + if (pardes.builtins.registry.scope(b) == .session) return false; + // A new pane is every tag's to make, in the session's directory. + if (b == .New or b == .Term) return false; + var words = std.mem.tokenizeScalar(u8, own, ' '); + while (words.next()) |w| if (std.mem.eql(u8, w, word)) return false; + return true; +} + +/// rmdir of a column closes it when it is empty; one with panes is +/// refused, saying so (close them, or Delcol on its ctl, which asks first). +pub fn remove(p: *Pardes, req: Req, serial: u32, file: tree.ColFile) Reply { + if (file != .dir) return Reply.fail(req.tag, E.PERM); + const col = layout.columnBySerial(p, serial) orelse return Reply.fail(req.tag, E.NOENT); + if (p.view().cols[col].n > 0) return tree.failText(req.tag, E.NOTEMPTY, "column not empty: close its panes, or write Delcol to its ctl"); + layout.removeColumn(p, col) catch return Reply.fail(req.tag, E.IO); + return .{ .tag = req.tag }; +} + +// ---- tests ---- + +const testing = std.testing; +const th = @import("testing.zig"); +const Node = tree.Node; + test "New written to a column's exec makes its scratch in the session's directory, as tagexec's does" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); @@ -369,22 +401,6 @@ test "New written to a column's ctl reads back the new pane alone, as its exec d try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{p.panes[p.view().active].?.serial}), th.rd(p, root_exec, 0, 64).bytes); } -/// Whether `line` names a builtin that acts on a pane (every one of pane -/// scope, Edit too, which the root's ctl takes at the active pane) and is -/// not one of `own`, the words its tag holds by default: those a tag no -/// pane owns refuses, never doing them at the pane with the keyboard. -fn paneWord(line: []const u8, own: []const u8) bool { - const cmd = pardes.exec.commandText(line); - const word = cmd[0 .. std.mem.indexOfAny(u8, cmd, " \t+") orelse cmd.len]; - const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), word) orelse return false; - if (pardes.builtins.registry.scope(b) == .session) return false; - // A new pane is every tag's to make, in the session's directory. - if (b == .New or b == .Term) return false; - var words = std.mem.tokenizeScalar(u8, own, ' '); - while (words.next()) |w| if (std.mem.eql(u8, w, word)) return false; - return true; -} - test "a pane's word written to /tagexec or a column's exec is refused, and acts on no pane" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); @@ -491,22 +507,6 @@ test "every pane word a tag no pane owns does not hold is refused there, Edit in try testing.expectEqualStrings("keep me\n", p.panes[0].?.file.?.content); } -/// rmdir of a column closes it when it is empty; one with panes is -/// refused, saying so (close them, or Delcol on its ctl, which asks first). -pub fn remove(p: *Pardes, req: Req, serial: u32, file: tree.ColFile) Reply { - if (file != .dir) return Reply.fail(req.tag, E.PERM); - const col = layout.columnBySerial(p, serial) orelse return Reply.fail(req.tag, E.NOENT); - if (p.view().cols[col].n > 0) return tree.failText(req.tag, E.NOTEMPTY, "column not empty: close its panes, or write Delcol to its ctl"); - layout.removeColumn(p, col) catch return Reply.fail(req.tag, E.IO); - return .{ .tag = req.tag }; -} - -// ---- tests ---- - -const testing = std.testing; -const th = @import("testing.zig"); -const Node = tree.Node; - test "layout lists each column's place, panes and state, and the active one" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index b00df909..20cb4e6e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -592,37 +592,6 @@ fn editSpan(old: []const u8, off: usize, len: usize, bytes: []const u8) Span { return .{ .at = @intCast(head), .removed = @intCast(old.len - tail - head), .inserted = @intCast(n - tail - head) }; } -test "an edit's span is where the texts before and after it differ" { - const reference = struct { - fn span(old: []const u8, new: []const u8) Span { - const both = @min(old.len, new.len); - var head: usize = 0; - while (head < both and old[head] == new[head]) head += 1; - var tail: usize = 0; - while (tail < both - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; - return .{ .at = @intCast(head), .removed = @intCast(old.len - tail - head), .inserted = @intCast(new.len - tail - head) }; - } - }.span; - var prng = std.Random.DefaultPrng.init(3); - const r = prng.random(); - var old: [24]u8 = undefined; - var new: [48]u8 = undefined; - var bytes: [24]u8 = undefined; - for (0..20000) |_| { - const old_len = r.uintAtMost(usize, old.len); - for (old[0..old_len]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)]; - const off = r.uintAtMost(usize, old_len); - const len = r.uintAtMost(usize, old_len - off); - const n = r.uintAtMost(usize, bytes.len); - for (bytes[0..n]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)]; - @memcpy(new[0..off], old[0..off]); - @memcpy(new[off..][0..n], bytes[0..n]); - @memcpy(new[off + n ..][0 .. old_len - off - len], old[off + len .. old_len]); - const new_len = old_len - len + n; - try std.testing.expectEqual(reference(old[0..old_len], new[0..new_len]), editSpan(old[0..old_len], off, len, bytes[0..n])); - } -} - /// Records ` ` for a pane a /// script reads; a text of max_record_text and over is sent as none. One /// that follows another with no place of its own (a chorded exec's @@ -859,6 +828,51 @@ const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; +fn drainEvents(p: *Pardes, node: u64, store: []u8, out: [][]const u8) [][]const u8 { + var used: usize = 0; + var n: usize = 0; + while (n < out.len) { + const a = rd(p, node, 0, 4096); + if (a.reply.status != .ok) break; + @memcpy(store[used..][0..a.bytes.len], a.bytes); + out[n] = store[used..][0..a.bytes.len]; + used += a.bytes.len; + n += 1; + } + return out[0..n]; +} + +test "an edit's span is where the texts before and after it differ" { + const reference = struct { + fn span(old: []const u8, new: []const u8) Span { + const both = @min(old.len, new.len); + var head: usize = 0; + while (head < both and old[head] == new[head]) head += 1; + var tail: usize = 0; + while (tail < both - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + return .{ .at = @intCast(head), .removed = @intCast(old.len - tail - head), .inserted = @intCast(new.len - tail - head) }; + } + }.span; + var prng = std.Random.DefaultPrng.init(3); + const r = prng.random(); + var old: [24]u8 = undefined; + var new: [48]u8 = undefined; + var bytes: [24]u8 = undefined; + for (0..20000) |_| { + const old_len = r.uintAtMost(usize, old.len); + for (old[0..old_len]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)]; + const off = r.uintAtMost(usize, old_len); + const len = r.uintAtMost(usize, old_len - off); + const n = r.uintAtMost(usize, bytes.len); + for (bytes[0..n]) |*c| c.* = "ab"[r.uintLessThan(usize, 2)]; + @memcpy(new[0..off], old[0..off]); + @memcpy(new[off..][0..n], bytes[0..n]); + @memcpy(new[off + n ..][0 .. old_len - off - len], old[off + len .. old_len]); + const new_len = old_len - len + n; + try std.testing.expectEqual(reference(old[0..old_len], new[0..new_len]), editSpan(old[0..old_len], off, len, bytes[0..n])); + } +} + test "a stream read at an offset inside its last answer gets the rest of it again, as bash's read seeks back" { const p = try withFile(testing.allocator, "one\n"); defer p.deinit(); @@ -921,20 +935,6 @@ test "event records are acme's bytes, one per read, and .again when empty" { try testing.expectEqual(@as(u16, 0), p.fs.listeners); } -fn drainEvents(p: *Pardes, node: u64, store: []u8, out: [][]const u8) [][]const u8 { - var used: usize = 0; - var n: usize = 0; - while (n < out.len) { - const a = rd(p, node, 0, 4096); - if (a.reply.status != .ok) break; - @memcpy(store[used..][0..a.bytes.len], a.bytes); - out[n] = store[used..][0..a.bytes.len]; - used += a.bytes.len; - n += 1; - } - return out[0..n]; -} - test "a write through the filesystem is reported once, attributed to the file it came through" { const gpa = testing.allocator; const p = try withFile(gpa, "one\ntwo\n"); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 58b14c92..519e5333 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -305,38 +305,6 @@ pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const return take; } -test "rows through the line index are the ones counting newlines gives, at every offset" { - const p = try withFile(testing.allocator, "héllo\nwo\u{301}rld\n\n last line é\ntail"); - defer p.deinit(); - const pane = p.panes[0].?; - const f = &pane.file.?; - _ = try panes.File.lineIndex(p.gpa, f); - const text = bodyOf(pane); - try testing.expect(lineIndex(pane, text) != null); - for (0..text.len + 2) |off| { - try testing.expectEqual(modal.positionAt(text, off), positionAt(pane, text, off)); - try testing.expectEqual(modal.runePositionAt(text, off), runePositionAt(pane, text, off)); - } - for (0..8) |row| for (0..16) |col| { - const c: modal.Cursor = .{ .row = row, .col = col }; - try testing.expectEqual(modal.runeOffsetAt(text, c), runeOffsetAt(pane, text, c)); - }; -} - -test "a terminal's body stats as long as it reads" { - const gpa = testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.isTerminal()); - p.update(.{ .output = .{ .pane = 0, .bytes = "$ ls\r\nalpha beta\r\n$ " } }); - const body = Node.of(pane.serial, .body); - const whole = rd(p, body, 0, 1 << 16); - try testing.expect(whole.bytes.len > 0); - try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = body }).reply.attr.size); -} - // ---- what stat reports ---- /// A range file's text: acme's addr format, two right-aligned offsets, so @@ -1027,6 +995,38 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Status = tree.Status; +test "rows through the line index are the ones counting newlines gives, at every offset" { + const p = try withFile(testing.allocator, "héllo\nwo\u{301}rld\n\n last line é\ntail"); + defer p.deinit(); + const pane = p.panes[0].?; + const f = &pane.file.?; + _ = try panes.File.lineIndex(p.gpa, f); + const text = bodyOf(pane); + try testing.expect(lineIndex(pane, text) != null); + for (0..text.len + 2) |off| { + try testing.expectEqual(modal.positionAt(text, off), positionAt(pane, text, off)); + try testing.expectEqual(modal.runePositionAt(text, off), runePositionAt(pane, text, off)); + } + for (0..8) |row| for (0..16) |col| { + const c: modal.Cursor = .{ .row = row, .col = col }; + try testing.expectEqual(modal.runeOffsetAt(text, c), runeOffsetAt(pane, text, c)); + }; +} + +test "a terminal's body stats as long as it reads" { + const gpa = testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.isTerminal()); + p.update(.{ .output = .{ .pane = 0, .bytes = "$ ls\r\nalpha beta\r\n$ " } }); + const body = Node.of(pane.serial, .body); + const whole = rd(p, body, 0, 1 << 16); + try testing.expect(whole.bytes.len > 0); + try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = body }).reply.attr.size); +} + test "a body write to a terminal pane types at its shell" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index dfcf7097..f7ca0cb7 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -519,29 +519,6 @@ pub fn fitErr(text: []const u8, out: []u8) []const u8 { return std.fmt.bufPrint(out, "{s}" ++ ell ++ "{s}", .{ text[0..a], text[b..] }) catch text[0..out.len]; } -test "a reason past 128 bytes keeps its end: the path in it gives up its middle" { - var out: [128]u8 = undefined; - const long = "Save /home/someone/projects/" ++ std.mem.asBytes(&@as([30][5]u8, @splat("deep/".*))) ++ "file.txt: no such directory"; - const fit = fitErr(long, &out); - try testing.expect(fit.len <= 128); - try testing.expect(std.mem.startsWith(u8, fit, "Save /home/someone/")); - try testing.expect(std.mem.endsWith(u8, fit, "file.txt: no such directory")); - try testing.expect(std.mem.indexOf(u8, fit, "…") != null); - try testing.expect(std.unicode.utf8ValidateSlice(fit)); - // No path: the whole text's middle goes, the end stays. - const words = std.mem.asBytes(&@as([40][4]u8, @splat("why ".*))) ++ "the reason"; - try testing.expect(std.mem.endsWith(u8, fitErr(words, &out), "the reason")); - try testing.expectEqualStrings("short", fitErr("short", &out)); - // Through the tree: a look at a long ./ name not there, a miss, says - // why at the end of its err record, the name giving up its middle. - const p = try th.withFile(testing.allocator, "x\n"); - defer p.deinit(); - var line: [512]u8 = undefined; - const r = th.wr(p, Node.of(serialOf(p), .look), try std.fmt.bufPrint(&line, "./{s}x.txt\n", .{std.mem.asBytes(&@as([20][12]u8, @splat("no-such-dir/".*)))})); - try testing.expectEqual(Status.ok, r.reply.status); - try testing.expect(th.logHas(p, "x.txt: no such file")); -} - /// A refusal with no reason of its own said in Plan 9's words, not the C /// library's (`Operation not permitted`); each maps back to its errno in /// 9ns (enameToErrno), EPERM's to EACCES as Plan 9's does. @@ -1383,17 +1360,6 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { // ---- tests ---- -test { - _ = events; - _ = pane; - _ = addr; - _ = ctl; - _ = pty; - _ = cols; - _ = sources; - _ = screen; -} - const testing = std.testing; const th = @import("testing.zig"); const config = @import("../config.zig"); @@ -1405,6 +1371,40 @@ const look_up = th.look_up; const withFile = th.withFile; const serialOf = th.serialOf; +test "a reason past 128 bytes keeps its end: the path in it gives up its middle" { + var out: [128]u8 = undefined; + const long = "Save /home/someone/projects/" ++ std.mem.asBytes(&@as([30][5]u8, @splat("deep/".*))) ++ "file.txt: no such directory"; + const fit = fitErr(long, &out); + try testing.expect(fit.len <= 128); + try testing.expect(std.mem.startsWith(u8, fit, "Save /home/someone/")); + try testing.expect(std.mem.endsWith(u8, fit, "file.txt: no such directory")); + try testing.expect(std.mem.indexOf(u8, fit, "…") != null); + try testing.expect(std.unicode.utf8ValidateSlice(fit)); + // No path: the whole text's middle goes, the end stays. + const words = std.mem.asBytes(&@as([40][4]u8, @splat("why ".*))) ++ "the reason"; + try testing.expect(std.mem.endsWith(u8, fitErr(words, &out), "the reason")); + try testing.expectEqualStrings("short", fitErr("short", &out)); + // Through the tree: a look at a long ./ name not there, a miss, says + // why at the end of its err record, the name giving up its middle. + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + var line: [512]u8 = undefined; + const r = th.wr(p, Node.of(serialOf(p), .look), try std.fmt.bufPrint(&line, "./{s}x.txt\n", .{std.mem.asBytes(&@as([20][12]u8, @splat("no-such-dir/".*)))})); + try testing.expectEqual(Status.ok, r.reply.status); + try testing.expect(th.logHas(p, "x.txt: no such file")); +} + +test { + _ = events; + _ = pane; + _ = addr; + _ = ctl; + _ = pty; + _ = cols; + _ = sources; + _ = screen; +} + test "a listing read in chunks is what it was at the open, however the panes change between reads" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/panes.zig b/src/panes.zig index 6b6f621a..f1bb46c8 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -699,17 +699,6 @@ pub const mini = @import("mini.zig"); pub const terminal = @import("terminal.zig"); -test { - _ = Pane; - _ = Text; - _ = File; - _ = Output; - _ = Dir; - _ = mini; - _ = @import("Kind.zig"); - _ = terminal; -} - // ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ---- const tutor_text = @embedFile("tutor.txt"); @@ -1115,6 +1104,17 @@ pub fn promptTarget(p: *Pardes, pane: *Pane) ?*Text { }; } +test { + _ = Pane; + _ = Text; + _ = File; + _ = Output; + _ = Dir; + _ = mini; + _ = @import("Kind.zig"); + _ = terminal; +} + test "owned cwd preserves long paths aliases and failed updates" { var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); diff --git a/src/pardes.zig b/src/pardes.zig index 2fa1d390..e9d38ad2 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -202,113 +202,6 @@ fn colFromSpan(x: f32, span: f32) u16 { return @intFromFloat(@min(@floor(@max(x, 0) / span), 10_000)); } -test "a compact tagline anchors at its own pane, and both shells step from the same origin" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 24 }); - defer p.deinit(); - _ = try p.newShell(1, ""); - try std.testing.expect(layout.splitColumn(p, 0, 1, false)); - p.sync(); - - // Two panes side by side put two tags on ONE row, which is the case a - // per-row origin gets wrong and the reason this is asked per cell. - const left = p.view().rects[0]; - const right = p.view().rects[1]; - try std.testing.expect(right.x > left.x); - try std.testing.expectEqual(@as(f32, @floatFromInt(left.x)), taglineOriginCol(p, left.x + 3, left.y)); - try std.testing.expectEqual(@as(f32, @floatFromInt(right.x)), taglineOriginCol(p, right.x + 3, right.y)); - - // The topbar's origin is column zero always — it is not a pane rect, which - // is why row zero is right even in a window with no core to ask. - try std.testing.expectEqual(@as(f32, 0), taglineOriginCol(p, 40, 0)); - - const body_row = left.y + 2; - try std.testing.expectEqual(@as(f32, 7), taglineOriginCol(p, 7, body_row)); - - const body_w: f32 = 10; - const tag_w: f32 = 8; - for (p.view().col_x[0..p.view().ncol], p.view().col_w[0..p.view().ncol]) |origin, width| { - if (width == 0) continue; - const col = origin; - try std.testing.expectEqual(@as(f32, @floatFromInt(origin)), taglineOriginCol(p, col, TOPBAR_H)); - const glyph_x = @as(f32, @floatFromInt(origin)) * body_w; - try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, TOPBAR_H, body_w, tag_w)); - } - for ([_]u16{ 0, 1, 5, 40, 119 }) |col| { - const origin = taglineOriginCol(p, col, left.y); - const sdl = origin * (body_w - tag_w) + @as(f32, @floatFromInt(col)) * tag_w; - const appkit = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; - try std.testing.expectEqual(sdl, appkit); - } - - for ([_]u16{ 0, 1, 4, 9 }) |offset| { - const col = left.x + offset; - if (offset >= left.w) break; - const origin = taglineOriginCol(p, col, left.y); - const glyph_x = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; - try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, left.y, body_w, tag_w)); - } - - // The topbar's pointer grid is compact from column zero, with no pane to - // anchor to — the one tag row that is right with or without a core. - try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * tag_w, 0, body_w, tag_w)); - try std.testing.expectEqual(@as(u16, 3), gridColAt(null, 3.5 * tag_w, 0, body_w, tag_w)); - - // A body row is untouched: still the body grid, still divided by the body - // cell. Only tag rows compact. - try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * body_w, body_row, body_w, tag_w)); -} - -test { - _ = @import("Addon.zig"); - _ = @import("rollback.zig"); - _ = @import("Core.zig"); - _ = @import("lsp/Ask.zig"); - _ = @import("Jump.zig"); - _ = @import("keys.zig"); - _ = @import("Effect.zig"); - _ = @import("tape.zig"); - _ = @import("replica.zig"); - _ = @import("echo.zig"); - _ = @import("modal.zig"); - _ = @import("tagline.zig"); - _ = @import("hunks.zig"); - _ = @import("builtins_json.zig"); - _ = @import("exec.zig"); - _ = @import("look.zig"); - _ = @import("sam_edit.zig"); - _ = @import("edit_cmd.zig"); - _ = @import("mouse.zig"); - _ = @import("normal.zig"); - _ = @import("regexp.zig"); - _ = @import("edit.zig"); - _ = @import("Messages.zig"); - _ = @import("Registers.zig"); - _ = @import("Macro.zig"); - _ = @import("selection_pipe.zig"); - _ = @import("Pipe.zig"); - _ = @import("colors.zig"); - _ = @import("surface.zig"); - _ = @import("glide.zig"); - _ = @import("body_layer.zig"); - _ = @import("draw.zig"); - _ = @import("dump.zig"); // its tests ran nowhere before - _ = @import("upgrade.zig"); - _ = @import("recent.zig"); - _ = @import("Store.zig"); - _ = @import("Db.zig"); - _ = @import("pager.zig"); - _ = @import("Places.zig"); - _ = @import("FrameStats.zig"); - _ = @import("Query.zig"); - _ = @import("Names.zig"); - _ = @import("Stream.zig"); - _ = @import("Tables.zig"); - _ = @import("Handover.zig"); - _ = @import("walk.zig"); - _ = screen_state; - _ = @import("views.zig"); -} - pub const Builtin = builtins.registry.Builtin(); pub const test_api = if (@import("builtin").is_test) struct { @@ -443,3 +336,109 @@ pub const Options = Pardes.Options; pub const Boot = Pardes.Boot; pub const Haptic = Pardes.Haptic; +test "a compact tagline anchors at its own pane, and both shells step from the same origin" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 24 }); + defer p.deinit(); + _ = try p.newShell(1, ""); + try std.testing.expect(layout.splitColumn(p, 0, 1, false)); + p.sync(); + + // Two panes side by side put two tags on ONE row, which is the case a + // per-row origin gets wrong and the reason this is asked per cell. + const left = p.view().rects[0]; + const right = p.view().rects[1]; + try std.testing.expect(right.x > left.x); + try std.testing.expectEqual(@as(f32, @floatFromInt(left.x)), taglineOriginCol(p, left.x + 3, left.y)); + try std.testing.expectEqual(@as(f32, @floatFromInt(right.x)), taglineOriginCol(p, right.x + 3, right.y)); + + // The topbar's origin is column zero always — it is not a pane rect, which + // is why row zero is right even in a window with no core to ask. + try std.testing.expectEqual(@as(f32, 0), taglineOriginCol(p, 40, 0)); + + const body_row = left.y + 2; + try std.testing.expectEqual(@as(f32, 7), taglineOriginCol(p, 7, body_row)); + + const body_w: f32 = 10; + const tag_w: f32 = 8; + for (p.view().col_x[0..p.view().ncol], p.view().col_w[0..p.view().ncol]) |origin, width| { + if (width == 0) continue; + const col = origin; + try std.testing.expectEqual(@as(f32, @floatFromInt(origin)), taglineOriginCol(p, col, TOPBAR_H)); + const glyph_x = @as(f32, @floatFromInt(origin)) * body_w; + try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, TOPBAR_H, body_w, tag_w)); + } + for ([_]u16{ 0, 1, 5, 40, 119 }) |col| { + const origin = taglineOriginCol(p, col, left.y); + const sdl = origin * (body_w - tag_w) + @as(f32, @floatFromInt(col)) * tag_w; + const appkit = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; + try std.testing.expectEqual(sdl, appkit); + } + + for ([_]u16{ 0, 1, 4, 9 }) |offset| { + const col = left.x + offset; + if (offset >= left.w) break; + const origin = taglineOriginCol(p, col, left.y); + const glyph_x = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; + try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, left.y, body_w, tag_w)); + } + + // The topbar's pointer grid is compact from column zero, with no pane to + // anchor to — the one tag row that is right with or without a core. + try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * tag_w, 0, body_w, tag_w)); + try std.testing.expectEqual(@as(u16, 3), gridColAt(null, 3.5 * tag_w, 0, body_w, tag_w)); + + // A body row is untouched: still the body grid, still divided by the body + // cell. Only tag rows compact. + try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * body_w, body_row, body_w, tag_w)); +} + +test { + _ = @import("Addon.zig"); + _ = @import("rollback.zig"); + _ = @import("Core.zig"); + _ = @import("lsp/Ask.zig"); + _ = @import("Jump.zig"); + _ = @import("keys.zig"); + _ = @import("Effect.zig"); + _ = @import("tape.zig"); + _ = @import("replica.zig"); + _ = @import("echo.zig"); + _ = @import("modal.zig"); + _ = @import("tagline.zig"); + _ = @import("hunks.zig"); + _ = @import("builtins_json.zig"); + _ = @import("exec.zig"); + _ = @import("look.zig"); + _ = @import("sam_edit.zig"); + _ = @import("edit_cmd.zig"); + _ = @import("mouse.zig"); + _ = @import("normal.zig"); + _ = @import("regexp.zig"); + _ = @import("edit.zig"); + _ = @import("Messages.zig"); + _ = @import("Registers.zig"); + _ = @import("Macro.zig"); + _ = @import("selection_pipe.zig"); + _ = @import("Pipe.zig"); + _ = @import("colors.zig"); + _ = @import("surface.zig"); + _ = @import("glide.zig"); + _ = @import("body_layer.zig"); + _ = @import("draw.zig"); + _ = @import("dump.zig"); // its tests ran nowhere before + _ = @import("upgrade.zig"); + _ = @import("recent.zig"); + _ = @import("Store.zig"); + _ = @import("Db.zig"); + _ = @import("pager.zig"); + _ = @import("Places.zig"); + _ = @import("FrameStats.zig"); + _ = @import("Query.zig"); + _ = @import("Names.zig"); + _ = @import("Stream.zig"); + _ = @import("Tables.zig"); + _ = @import("Handover.zig"); + _ = @import("walk.zig"); + _ = screen_state; + _ = @import("views.zig"); +} diff --git a/src/replica.zig b/src/replica.zig index 5b2facb4..1499d166 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -2266,9 +2266,9 @@ pub const Peers = struct { fn writeStats(ps: *Peers, path: []const u8) void { var buf: [400]u8 = undefined; const line = std.fmt.bufPrint(&buf, "session inputs {d} input_us {d}/{d}/{d} boundaries {d} boundary_us {d}/{d}/{d} join_us {d} dump_kb {d} state_kb {d} cut {d}\n", .{ - ps.input_ns.items.len, pctOf(ps.input_ns.items, 50) / 1000, pctOf(ps.input_ns.items, 99) / 1000, pctOf(ps.input_ns.items, 100) / 1000, - ps.boundary_ns.items.len, pctOf(ps.boundary_ns.items, 50) / 1000, pctOf(ps.boundary_ns.items, 99) / 1000, pctOf(ps.boundary_ns.items, 100) / 1000, - ps.join_ns / 1000, ps.dump_bytes >> 10, ps.state_bytes >> 10, ps.cut, + ps.input_ns.items.len, pctOf(ps.input_ns.items, 50) / 1000, pctOf(ps.input_ns.items, 99) / 1000, pctOf(ps.input_ns.items, 100) / 1000, + ps.boundary_ns.items.len, pctOf(ps.boundary_ns.items, 50) / 1000, pctOf(ps.boundary_ns.items, 99) / 1000, pctOf(ps.boundary_ns.items, 100) / 1000, + ps.join_ns / 1000, ps.dump_bytes >> 10, ps.state_bytes >> 10, ps.cut, }) catch return; var z: [4096]u8 = undefined; const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; @@ -2978,11 +2978,11 @@ pub const Link = struct { const e = &c.r.echo.stats; var w: std.Io.Writer = .fixed(&buf); w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d}", .{ - st.inputs, st.speculated, st.stopped, st.units, st.fast, - c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, - pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, - pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, - c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, + st.inputs, st.speculated, st.stopped, st.units, st.fast, + c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, + pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, + pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, + c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, }) catch return; // What stopped its inputs, last: a word a pair before it. w.writeAll(" stops ") catch return; @@ -3009,30 +3009,6 @@ pub const Link = struct { } }; -test "a message past the wire's bound is named, never read as the link's end" { - var fds: [2]c_int = undefined; - try std.testing.expectEqual(0, libc.pipe(&fds)); - const head = wire.header(@backingInt(wire.ServerTag.unit), wire.max_payload + 1); - _ = libc.write(fds[1], &head, head.len); - _ = libc.close(fds[1]); - var fr: Framer = .{}; - defer fr.deinit(std.testing.allocator); - fr.run(std.testing.allocator, fds[0], {}, struct { - fn take(_: void, _: u8, _: []const u8) bool { - return true; - } - }.take); - _ = libc.close(fds[0]); - try std.testing.expectEqual(wire.max_payload + 1, fr.overlong().?); -} - -test "a client joining again after a divergence is told at once that its session is gone" { - var why: [600]u8 = undefined; - const t0 = nowNs(); - try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null); - try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms); -} - fn appendTo(path: [:0]const u8, line: []const u8) void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return; @@ -3056,6 +3032,43 @@ const TestHost = struct { } }; +/// A host with ptys whose pump polls for a frame, as a client's does. +const PtyHost = struct { + fn resized(_: ?*anyopaque, _: u8, _: u16, _: u16) void {} + fn poll(_: ?*anyopaque) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_resize = resized, .poll_frame = poll }; + fn host() pardes.Host { + return .{ .vtable = &vtable }; + } +}; + +/// A kind as a library brings one, for the Shadow's test: a counter its +/// keys move, painted as `count N`. +const Counter = struct { + const pa = pardes.Kind.c; + fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { + return pardes.Kind.api.alloc.?(4); + } + fn paint(st: ?*anyopaque, win: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void { + const n: *u32 = @ptrCast(@alignCast(st.?)); + var line: [16]u8 = undefined; + const text = std.fmt.bufPrint(&line, "count {d}", .{n.*}) catch unreachable; + for (text, 0..) |ch, i| win.*.cells[i] = std.mem.zeroInit(pa.pa_cell, .{ .text = .{ ch, 0, 0, 0, 0, 0, 0, 0 }, .len = 1, .flags = pa.PA_PAINTED, .fg = pa.PA_DEFAULT, .bg = pa.PA_DEFAULT }); + } + fn press(st: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { + const n: *u32 = @ptrCast(@alignCast(st.?)); + n.* += 1; + return 1; + } + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Counter", .opens = 1, .doc = "a counter" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "counter".* ++ @as([9]u8, @splat(0)), .version = 1, .exts = "", .words = &words, .nwords = 1 }), + .open = open, + .paint = paint, + .key = press, + }); +}; + /// An edit's file time is the clock's second, which a replica guesses: a /// second's turn between a key and the authority's take of it is a fair /// misprediction (11 runs in 40 of a loaded Debug window build's test @@ -3075,6 +3088,196 @@ fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void { try sent.append(std.testing.allocator, try std.testing.allocator.dupe(u8, msg)); } +/// What the session sends a peer: its terminals' changes (`.flush`), or, +/// around a step's unit (Peers.input), the rows the step read that the +/// peer lacks (`.fill`), after which the caller gives terminals the sizes +/// the step gave them (`terminal.resizeDeferred`), then the unit. +fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime what: enum { flush, fill }) !void { + const gpa = std.testing.allocator; + var msgs: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (msgs.items) |m| gpa.free(m); + msgs.deinit(gpa); + } + switch (what) { + .flush => try screens.flush(a.core, peer, r.view, &msgs), + .fill => { + try screens.fill(a.core, peer, &msgs); + screens.filled(a.core); + }, + } + for (msgs.items) |m| if (r.screen(m)) |reply| { + _ = try screens.take(a.core, peer, reply); + }; +} + +/// The blob cache of a test, in its own directory (never the user's). +fn testCache(tmp: *std.testing.TmpDir, buf: *[4200]u8, cap: u64) !Cache { + var dir_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + return Cache.of(try std.fmt.bufPrint(buf, "{s}/" ++ Cache.name, .{dir}), cap); +} + +/// A far join over a socket pair, the session's writer and reader threads +/// against the client's `joinOn`, as the daemon hands a connection over: +/// its hello read off first. +fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + const state = pardes.dump.dumpJoin(core, &blobs) catch |err| { + _ = libc.close(fds[0]); + _ = libc.close(fds[1]); + return err; + }; + var whole = state.len; + for (blobs.items) |b| whole += b.bytes.len; + const peer = try ps.gpa.create(Peer); + peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = 0, .dump = state, .blobs = blobs, .dump_gpa = core.gpa }; + peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; + const Serve = struct { + fn run(p: *Peer) void { + var hello: [wire.header_len + 14]u8 = undefined; + var got: usize = 0; + while (got < hello.len) { + const n = libc.read(p.fd, hello[got..].ptr, hello.len - got); + if (n <= 0) return p.peers.post(.{ .gone = p }); + got += @intCast(n); + } + p.readLoop(); + } + }; + peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); + peer.reader = try std.Thread.spawn(.{}, Serve.run, .{peer}); + defer ps.letGo(peer); + var why: [300]u8 = @splat(0); + return joinOn(std.testing.allocator, fds[1], "t", &why, have, null) orelse { + std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); + return error.JoinFailed; + }; +} + +fn endJoin(j: *Joined, have: ?*Have) void { + _ = libc.close(j.fd); + j.rest.deinit(std.testing.allocator); + if (have) |h| { + h.store(std.testing.allocator, j); + h.wait(); + } else { + std.testing.allocator.free(j.dump); + std.heap.c_allocator.free(j.got); + } +} + +/// A replica joined from the session's dump as it is now, between units, +/// as `Peers.join` sends it: its state, its blobs put back where they go. +fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { + const gpa = std.testing.allocator; + const was = Stepping.begin(&a.t, null); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(a.core.gpa); + const state = try pardes.dump.dumpJoin(a.core, &blobs); + defer a.core.gpa.free(state); + tape.resync(&a.t); + was.end(); + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(gpa, state[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, state[pos..]); + return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); +} + +fn agrees(a: *Authority, r: *Replica) !void { + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expect(r.quiet()); + try std.testing.expectEqual(digestOf(a), r.digest()); +} + +fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 { + const n = (try wire.encodeClient(buf[head_len..], .{ .event = ev })).len; + header(buf, client, seq); + return buf[0 .. head_len + n]; +} + +/// An input of a replica's in the session's order, as `Peers.input` takes +/// it: the terminals flushed to every peer, the step, the rows it read that +/// each peer holds as holes (`fill`), then its unit to every replica. +fn takeAll(a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, msg: []const u8) !void { + const gpa = std.testing.allocator; + for (rs, ps) |r, peer| try deliver(a, screens, peer, r, .flush); + const u = try gpa.dupe(u8, try a.take(msg)); + defer gpa.free(u); + var rows: std.ArrayListUnmanaged([]u8) = .empty; + defer rows.deinit(gpa); + for (rs, ps) |r, peer| { + rows.clearRetainingCapacity(); + try screens.fill(a.core, peer, &rows); + for (rows.items) |m| { + _ = r.screen(m); + gpa.free(m); + } + } + screens.filled(a.core); + for (rs) |r| { + r.confirm(u); + r.settle(); + } +} + +fn sendAs(r: *Replica, a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, ev: pardes.Event) !void { + const msg = try std.testing.allocator.dupe(u8, try r.input(ev)); + defer std.testing.allocator.free(msg); + try takeAll(a, screens, rs, ps, msg); +} + +fn shows(p: *Pardes, text: []const u8) !bool { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + var row: [512]u8 = undefined; + for (0..s.rows) |y| { + var n: usize = 0; + for (0..s.cols) |x| { + const g = s.at(@intCast(x), @intCast(y)).grapheme(); + if (n + g.len > row.len) break; + @memcpy(row[n..][0..g.len], g); + n += g.len; + } + if (std.mem.indexOf(u8, row[0..n], text) != null) return true; + } + return false; +} + +test "a message past the wire's bound is named, never read as the link's end" { + var fds: [2]c_int = undefined; + try std.testing.expectEqual(0, libc.pipe(&fds)); + const head = wire.header(@backingInt(wire.ServerTag.unit), wire.max_payload + 1); + _ = libc.write(fds[1], &head, head.len); + _ = libc.close(fds[1]); + var fr: Framer = .{}; + defer fr.deinit(std.testing.allocator); + fr.run(std.testing.allocator, fds[0], {}, struct { + fn take(_: void, _: u8, _: []const u8) bool { + return true; + } + }.take); + _ = libc.close(fds[0]); + try std.testing.expectEqual(wire.max_payload + 1, fr.overlong().?); +} + +test "a client joining again after a divergence is told at once that its session is gone" { + var why: [600]u8 = undefined; + const t0 = nowNs(); + try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null); + try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms); +} + test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); @@ -3417,29 +3620,6 @@ test "a terminal sized again by a client's key: the step reads the grid it had, try std.testing.expectEqual(digestOf(a), r.digest()); } -/// What the session sends a peer: its terminals' changes (`.flush`), or, -/// around a step's unit (Peers.input), the rows the step read that the -/// peer lacks (`.fill`), after which the caller gives terminals the sizes -/// the step gave them (`terminal.resizeDeferred`), then the unit. -fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime what: enum { flush, fill }) !void { - const gpa = std.testing.allocator; - var msgs: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (msgs.items) |m| gpa.free(m); - msgs.deinit(gpa); - } - switch (what) { - .flush => try screens.flush(a.core, peer, r.view, &msgs), - .fill => { - try screens.fill(a.core, peer, &msgs); - screens.filled(a.core); - }, - } - for (msgs.items) |m| if (r.screen(m)) |reply| { - _ = try screens.take(a.core, peer, reply); - }; -} - test "pardes's own keys over a terminal's history apply at once: its view moves here, a delta while they wait puts them on top again, the authority's ends the same" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); @@ -3467,7 +3647,7 @@ test "pardes's own keys over a terminal's history apply at once: its view moves // Normal mode in the shell, up a few rows, then half a screen and more: // the cursor leaves the view, and the view follows it back. const keys = [_]pardes.Key{ - .{ .cp = a.core.opts.tty_toggle, .ctrl = true }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'k', .text = "k" }, + .{ .cp = a.core.opts.tty_toggle, .ctrl = true }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'k', .text = "k" }, }; for (keys) |k| try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = k }))); @@ -3620,13 +3800,6 @@ test "a join's dump, its blobs put back where they go, is the session's dump" { try std.testing.expectEqualSlices(u8, whole, joined.items); } -/// The blob cache of a test, in its own directory (never the user's). -fn testCache(tmp: *std.testing.TmpDir, buf: *[4200]u8, cap: u64) !Cache { - var dir_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - return Cache.of(try std.fmt.bufPrint(buf, "{s}/" ++ Cache.name, .{dir}), cap); -} - test "a cached blob is hashed again as it is read: one kept cut short, corrupted, planted or longer is a miss, and goes" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -3718,57 +3891,6 @@ test "a blob cache that is no database is started afresh" { try std.testing.expect(c.get(io, &hash, &out)); } -/// A far join over a socket pair, the session's writer and reader threads -/// against the client's `joinOn`, as the daemon hands a connection over: -/// its hello read off first. -fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { - var fds: [2]c_int = undefined; - if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; - var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; - const state = pardes.dump.dumpJoin(core, &blobs) catch |err| { - _ = libc.close(fds[0]); - _ = libc.close(fds[1]); - return err; - }; - var whole = state.len; - for (blobs.items) |b| whole += b.bytes.len; - const peer = try ps.gpa.create(Peer); - peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = 0, .dump = state, .blobs = blobs, .dump_gpa = core.gpa }; - peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; - const Serve = struct { - fn run(p: *Peer) void { - var hello: [wire.header_len + 14]u8 = undefined; - var got: usize = 0; - while (got < hello.len) { - const n = libc.read(p.fd, hello[got..].ptr, hello.len - got); - if (n <= 0) return p.peers.post(.{ .gone = p }); - got += @intCast(n); - } - p.readLoop(); - } - }; - peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); - peer.reader = try std.Thread.spawn(.{}, Serve.run, .{peer}); - defer ps.letGo(peer); - var why: [300]u8 = @splat(0); - return joinOn(std.testing.allocator, fds[1], "t", &why, have, null) orelse { - std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); - return error.JoinFailed; - }; -} - -fn endJoin(j: *Joined, have: ?*Have) void { - _ = libc.close(j.fd); - j.rest.deinit(std.testing.allocator); - if (have) |h| { - h.store(std.testing.allocator, j); - h.wait(); - } else { - std.testing.allocator.free(j.dump); - std.heap.c_allocator.free(j.got); - } -} - test "a far join is sent each blob once: joined again with them on disk or in the core it leaves, the state alone; a cached file gone bad, that blob again" { const gpa = std.testing.allocator; const io = std.testing.io; @@ -3867,36 +3989,6 @@ test "a far join is sent each blob once: joined again with them on disk or in th endJoin(&j, &have); } -/// A replica joined from the session's dump as it is now, between units, -/// as `Peers.join` sends it: its state, its blobs put back where they go. -fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { - const gpa = std.testing.allocator; - const was = Stepping.begin(&a.t, null); - var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; - defer blobs.deinit(a.core.gpa); - const state = try pardes.dump.dumpJoin(a.core, &blobs); - defer a.core.gpa.free(state); - tape.resync(&a.t); - was.end(); - var whole: std.ArrayListUnmanaged(u8) = .empty; - defer whole.deinit(gpa); - var pos: usize = 0; - for (blobs.items) |b| { - try whole.appendSlice(gpa, state[pos..b.at]); - try whole.appendSlice(gpa, b.bytes); - pos = b.at; - } - try whole.appendSlice(gpa, state[pos..]); - return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); -} - -fn agrees(a: *Authority, r: *Replica) !void { - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null); - try std.testing.expect(r.quiet()); - try std.testing.expectEqual(digestOf(a), r.digest()); -} - test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); @@ -3968,22 +4060,6 @@ test "a replica's Del of a file its session's Recent knows asks the host what th try agrees(a, r); } -/// A host with ptys whose pump polls for a frame, as a client's does. -const PtyHost = struct { - fn resized(_: ?*anyopaque, _: u8, _: u16, _: u16) void {} - fn poll(_: ?*anyopaque) void {} - const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_resize = resized, .poll_frame = poll }; - fn host() pardes.Host { - return .{ .vtable = &vtable }; - } -}; - -fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 { - const n = (try wire.encodeClient(buf[head_len..], .{ .event = ev })).len; - header(buf, client, seq); - return buf[0 .. head_len + n]; -} - test "a client leaves, and one joins: what the leave queued (a terminal's resize) is done in its unit, on every side, before the join's dump" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); @@ -4116,37 +4192,6 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } } -/// An input of a replica's in the session's order, as `Peers.input` takes -/// it: the terminals flushed to every peer, the step, the rows it read that -/// each peer holds as holes (`fill`), then its unit to every replica. -fn takeAll(a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, msg: []const u8) !void { - const gpa = std.testing.allocator; - for (rs, ps) |r, peer| try deliver(a, screens, peer, r, .flush); - const u = try gpa.dupe(u8, try a.take(msg)); - defer gpa.free(u); - var rows: std.ArrayListUnmanaged([]u8) = .empty; - defer rows.deinit(gpa); - for (rs, ps) |r, peer| { - rows.clearRetainingCapacity(); - try screens.fill(a.core, peer, &rows); - for (rows.items) |m| { - _ = r.screen(m); - gpa.free(m); - } - } - screens.filled(a.core); - for (rs) |r| { - r.confirm(u); - r.settle(); - } -} - -fn sendAs(r: *Replica, a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, ev: pardes.Event) !void { - const msg = try std.testing.allocator.dupe(u8, try r.input(ev)); - defer std.testing.allocator.free(msg); - try takeAll(a, screens, rs, ps, msg); -} - test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); @@ -4184,51 +4229,6 @@ test "a step that reads a terminal's rows as the core keeps them sends a new cli for ([_]*Replica{ r1, r2 }) |r| try agrees(a, r); } -/// A kind as a library brings one, for the Shadow's test: a counter its -/// keys move, painted as `count N`. -const Counter = struct { - const pa = pardes.Kind.c; - fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { - return pardes.Kind.api.alloc.?(4); - } - fn paint(st: ?*anyopaque, win: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void { - const n: *u32 = @ptrCast(@alignCast(st.?)); - var line: [16]u8 = undefined; - const text = std.fmt.bufPrint(&line, "count {d}", .{n.*}) catch unreachable; - for (text, 0..) |ch, i| win.*.cells[i] = std.mem.zeroInit(pa.pa_cell, .{ .text = .{ ch, 0, 0, 0, 0, 0, 0, 0 }, .len = 1, .flags = pa.PA_PAINTED, .fg = pa.PA_DEFAULT, .bg = pa.PA_DEFAULT }); - } - fn press(st: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { - const n: *u32 = @ptrCast(@alignCast(st.?)); - n.* += 1; - return 1; - } - const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Counter", .opens = 1, .doc = "a counter" })}; - const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ - .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "counter".* ++ @as([9]u8, @splat(0)), .version = 1, .exts = "", .words = &words, .nwords = 1 }), - .open = open, - .paint = paint, - .key = press, - }); -}; - -fn shows(p: *Pardes, text: []const u8) !bool { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const s = try p.render(arena.allocator()); - var row: [512]u8 = undefined; - for (0..s.rows) |y| { - var n: usize = 0; - for (0..s.cols) |x| { - const g = s.at(@intCast(x), @intCast(y)).grapheme(); - if (n + g.len > row.len) break; - @memcpy(row[n..][0..g.len], g); - n += g.len; - } - if (std.mem.indexOf(u8, row[0..n], text) != null) return true; - } - return false; -} - test "a replica with no code for a kind draws its pane from the authority's frames, and its keys go to the authority" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); diff --git a/src/sam_edit.zig b/src/sam_edit.zig index 3886f9eb..173a559b 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -1075,6 +1075,67 @@ pub fn moveDot(dot: Range, ops: []const Op) Range { return .{ .q0 = q0, .q1 = q1 }; } +/// Three files and a +Errors, the way the editor hands them over, and a +/// world whose disk holds /src/new.c and /src/data. +const Fixture = struct { + arena_state: std.heap.ArenaAllocator, + why: Why = .{}, + + const files = [_]File{ + .{ .name = "/src/a.c", .text = "int foo;\nint bar;\n", .id = 0 }, + .{ .name = "/src/b.h", .text = "foo bar foo\n", .id = 1, .dirty = true }, + .{ .name = "/src/c.c", .text = "bar\n", .id = 2 }, + .{ .name = "/src/+Errors", .text = "foo\n", .id = 3, .scratch = true }, + }; + + var opened: usize = 0; + + fn check(_: *anyopaque, path: []const u8, why: *Why) bool { + if (std.mem.eql(u8, path, "/src/new.c")) return true; + why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0; + return false; + } + + /// The edited file, b.h, is asked about: refused. + fn refuseGet(_: *anyopaque, id: usize, why: *Why) bool { + if (id != 1) return false; + why.len = (std.fmt.bufPrint(&why.buf, "/src/b.h: Modified (e again to discard)", .{}) catch unreachable).len; + return true; + } + + fn open(_: *anyopaque, path: []const u8, why: *Why) ?File { + opened += 1; + if (std.mem.eql(u8, path, "/src/new.c")) return .{ .name = "/src/new.c", .text = "new foo\n", .id = 9 }; + why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0; + return null; + } + + fn read(_: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8 { + if (std.mem.eql(u8, path, "/src/data")) return arena.dupe(u8, "DATA\n") catch null; + why.len = if (std.fmt.bufPrint(&why.buf, "can't open {s}: file does not exist", .{path})) |said| said.len else |_| 0; + return null; + } + + fn init() Fixture { + return .{ .arena_state = .init(std.testing.allocator) }; + } + + fn deinit(fx: *Fixture) void { + fx.arena_state.deinit(); + } + + fn edit(fx: *Fixture, from: usize, command: []const u8) !Result { + var ctx: u8 = 0; + const world: World = .{ .ctx = &ctx, .check = check, .open = open, .read = read, .refuseGet = refuseGet }; + return run(fx.arena_state.allocator(), &files, from, command, world, &fx.why); + } + + /// File `i`'s text after the Edit. + fn after(fx: *Fixture, res: Result, i: usize) ![]const u8 { + return apply(fx.arena_state.allocator(), res.files[i].text, res.files[i].ops.items); + } +}; + fn edited(text: []const u8, command: []const u8) ![]u8 { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -1199,67 +1260,6 @@ test "x, y and s match whole runes: a byte pattern never splits one" { try expectEdit("\u{e9}", ",s/$/!/", "\u{e9}!"); } -/// Three files and a +Errors, the way the editor hands them over, and a -/// world whose disk holds /src/new.c and /src/data. -const Fixture = struct { - arena_state: std.heap.ArenaAllocator, - why: Why = .{}, - - const files = [_]File{ - .{ .name = "/src/a.c", .text = "int foo;\nint bar;\n", .id = 0 }, - .{ .name = "/src/b.h", .text = "foo bar foo\n", .id = 1, .dirty = true }, - .{ .name = "/src/c.c", .text = "bar\n", .id = 2 }, - .{ .name = "/src/+Errors", .text = "foo\n", .id = 3, .scratch = true }, - }; - - var opened: usize = 0; - - fn check(_: *anyopaque, path: []const u8, why: *Why) bool { - if (std.mem.eql(u8, path, "/src/new.c")) return true; - why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0; - return false; - } - - /// The edited file, b.h, is asked about: refused. - fn refuseGet(_: *anyopaque, id: usize, why: *Why) bool { - if (id != 1) return false; - why.len = (std.fmt.bufPrint(&why.buf, "/src/b.h: Modified (e again to discard)", .{}) catch unreachable).len; - return true; - } - - fn open(_: *anyopaque, path: []const u8, why: *Why) ?File { - opened += 1; - if (std.mem.eql(u8, path, "/src/new.c")) return .{ .name = "/src/new.c", .text = "new foo\n", .id = 9 }; - why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0; - return null; - } - - fn read(_: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8 { - if (std.mem.eql(u8, path, "/src/data")) return arena.dupe(u8, "DATA\n") catch null; - why.len = if (std.fmt.bufPrint(&why.buf, "can't open {s}: file does not exist", .{path})) |said| said.len else |_| 0; - return null; - } - - fn init() Fixture { - return .{ .arena_state = .init(std.testing.allocator) }; - } - - fn deinit(fx: *Fixture) void { - fx.arena_state.deinit(); - } - - fn edit(fx: *Fixture, from: usize, command: []const u8) !Result { - var ctx: u8 = 0; - const world: World = .{ .ctx = &ctx, .check = check, .open = open, .read = read, .refuseGet = refuseGet }; - return run(fx.arena_state.allocator(), &files, from, command, world, &fx.why); - } - - /// File `i`'s text after the Edit. - fn after(fx: *Fixture, res: Result, i: usize) ![]const u8 { - return apply(fx.arena_state.allocator(), res.files[i].text, res.files[i].ops.items); - } -}; - test "X and Y run a command in each open file whose line matches, or does not" { var fx: Fixture = .init(); defer fx.deinit(); diff --git a/src/screen_state.zig b/src/screen_state.zig index 6b12f9eb..eeb1c059 100644 --- a/src/screen_state.zig +++ b/src/screen_state.zig @@ -70,7 +70,7 @@ pub fn rowHash(page: *Page, row: *Row, cols: u16) Hash { fn rowFlags(row: *const Row) u8 { return @as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 | - @as(u8, @intFromEnum(row.semantic_prompt)) << 2; + @as(u8, @backingInt(row.semantic_prompt)) << 2; } /// The authority's absolute row numbers for one terminal: its primary @@ -397,9 +397,9 @@ fn write(e: *Encoder, tr: *Track, base: ?*const Known, t: *Terminal, extra: []co try out.writeInt(u64, tr.meta_hash, .little); try out.writeInt(u16, screen.cursor.x, .little); try out.writeInt(u16, screen.cursor.y, .little); - try out.writeByte(@intFromEnum(screen.cursor.cursor_style)); + try out.writeByte(@backingInt(screen.cursor.cursor_style)); try out.writeByte(@intFromBool(screen.cursor.pending_wrap)); - try out.writeByte(@intFromEnum(screen.cursor.semantic_content)); + try out.writeByte(@backingInt(screen.cursor.semantic_content)); // ponytail: raw bytes, as the hello refuses a peer of another build. try out.writeAll(std.mem.asBytes(&screen.kitty_keyboard)); try out.writeInt(u64, top, .little); @@ -626,7 +626,7 @@ pub const Replica = struct { } const screen = t.screens.active; - const held = &r.held[@intFromEnum(t.screens.active_key)]; + const held = &r.held[@backingInt(t.screens.active_key)]; const blank_row = blankHash(t.cols); while (held.items.len < nrows) try held.append(gpa, blank_row); held.shrinkRetainingCapacity(nrows); @@ -638,9 +638,9 @@ pub const Replica = struct { } screen.cursorReload(); screen.cursorAbsolute(@min(cx, t.cols - 1), @min(cy, t.rows - 1)); - screen.cursor.cursor_style = @enumFromInt(style); + screen.cursor.cursor_style = @fromBackingInt(@intCast(style)); screen.cursor.pending_wrap = wrap != 0; - screen.cursor.semantic_content = @enumFromInt(semantic); + screen.cursor.semantic_content = @fromBackingInt(@intCast(semantic)); screen.kitty_keyboard = kitty; const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows); primary.pages.scroll(if (viewport == following) .active else .{ .row = @intCast(viewport -| oldest) }); @@ -833,10 +833,10 @@ pub fn dumpScreen(t: *Terminal, w: *std.Io.Writer) !void { const screen = t.screens.active; const sb = t.screens.get(.primary).?.pages.scrollbar(); try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{ - t.cols, t.rows, @tagName(t.screens.active_key), - screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style), - screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "", - t.getPwd() orelse "", sb.total, sb.offset, + t.cols, t.rows, @tagName(t.screens.active_key), + screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style), + screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "", + t.getPwd() orelse "", sb.total, sb.offset, sb.len, }); try w.writeAll(std.mem.asBytes(&t.modes.values)); @@ -1135,164 +1135,6 @@ pub fn yesStream(gpa: std.mem.Allocator, lines: usize) ![]u8 { return out; } -test "a replica's screen is its authority's, cell for cell, as states are skipped, resized and fetched" { - const gpa = testing.allocator; - const io = testing.io; - const shell = try shellStream(gpa); - defer gpa.free(shell); - const tui = try tuiStream(gpa); - defer gpa.free(tui); - const yes = try yesStream(gpa, 30_000); - defer gpa.free(yes); - var fetched: u64 = 0; - var history: u64 = 0; - for (0..4) |seed| { - // A small scrollback, so it wraps (pruned at its oldest pages). - for ([_][]const u8{ shell, tui, yes }) |bytes| { - const st = soak(gpa, io, bytes, 80, 24, 64 * 1024, seed, seed != 0) catch |err| { - std.debug.print("soak seed {d} stream {d} bytes: {s}\n", .{ seed, bytes.len, @errorName(err) }); - return err; - }; - try testing.expect(st.deltas > 10); - fetched += st.fetched; - history += st.history_checked; - } - } - // The holes were fetched, and history rows compared, at all. - try testing.expect(fetched > 0 and history > 0); -} - -test "under a flood a delta is a screen of hashes: an unchanged row costs its address alone" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 200, 60, 1 << 20, 1); - defer s.deinit(); - s.resizes = false; - s.drops = false; - const yes = try yesStream(gpa, 10_000); - defer gpa.free(yes); - var last: []u8 = &.{}; - defer gpa.free(last); - for (0..3) |_| { - s.stream.nextSlice(yes); - s.changes += 1; - try s.send(0); - try testing.expectEqual(@as(usize, 1), s.flight.items.len); - gpa.free(last); - last = try gpa.dupe(u8, s.flight.items[0].delta); - try s.land(); - } - // The last: 60 rows and the tail's 60, of hashes the replica holds, no - // blob; the header and counts around them. - const d = last; - const at = 4 + 4 + 1 + 4 + 8 + 2 + 2 + 1 + 1 + 1 + @sizeOf(KittyFlags) + 8 + 8 + 8 + 2 + "extra".len; - const nrows = std.mem.readInt(u16, d[at..][0..2], .little); - const tail = std.mem.readInt(u16, d[at + 2 + nrows * 8 ..][0..2], .little); - const blobs = std.mem.readInt(u16, d[at + 4 + (nrows + tail) * 8 ..][0..2], .little); - if (d.len >= (nrows + tail) * 8 + 128) std.debug.print("delta {d} bytes: {d} rows, {d} tail, {d} blobs\n", .{ d.len, nrows, tail, blobs }); - try testing.expectEqual(@as(u16, 0), blobs); - try testing.expect(d.len < (nrows + tail) * 8 + 128); - try testing.expect(s.rep.holes.items.len > 0); -} - -test "a reflow to fewer columns keeps every history row numbered at or past 0" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 3); - defer s.deinit(); - s.resizes = false; - s.drops = false; - // Lines of 69 columns scrolled into the history, then the screen - // narrowed so that each wraps in three: more rows above the last top - // than ever scrolled past it (a window client's font, 2026-10-30: the - // session's peer started afresh at `top - history`, which overflowed). - var line: [80]u8 = undefined; - for (0..200) |i| { - s.stream.nextSlice(try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i})); - s.changes += 1; - } - try s.send(0); - try s.land(); - try s.a.resize(gpa, .{ .cols = 30, .rows = 24 }); - s.changes += 1; - try s.send(0); - try s.land(); - try s.settle(); - try testing.expect(s.track.rows.top >= s.track.history); -} - -test "several deltas in flight land in order, and a peer at the bound waits for an acknowledgement" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 2); - defer s.deinit(); - s.resizes = false; - s.drops = false; - var line: [64]u8 = undefined; - for (0..bound + 5) |i| { - s.stream.nextSlice(try std.fmt.bufPrint(&line, "line {d}\r\n", .{i})); - s.changes += 1; - try s.send(1000); - } - // The bound's worth went; the rest wait, and are skipped. - try testing.expectEqual(@as(usize, bound), s.flight.items.len); - try s.land(); - try s.send(1000); - try testing.expectEqual(@as(usize, bound), s.flight.items.len); - try s.settle(); - try testing.expectEqual(@as(u64, 0), s.stats.refused); -} - -test "a replica's terminal pane draws as its authority's does" { - const pardes = @import("pardes.zig"); - const gpa = testing.allocator; - const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer a.deinit(); - const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer b.deinit(); - while (a.nextEffect()) |_| {} - while (b.nextEffect()) |_| {} - var fa = std.heap.ArenaAllocator.init(gpa); - defer fa.deinit(); - var fb = std.heap.ArenaAllocator.init(gpa); - defer fb.deinit(); - // Laid out once, so both panes have their size before the first delta. - _ = try a.render(fa.allocator()); - _ = try b.render(fb.allocator()); - const ta = &a.panes[0].?.terminal.?.vt; - const tb = &b.panes[0].?.terminal.?.vt; - var enc: Encoder = .init(gpa); - defer enc.deinit(); - var peer: Peer = .{}; - defer peer.deinit(gpa); - var tr: Track = .init(gpa); - defer tr.deinit(gpa, ta); - var rep: Replica = .{}; - defer rep.deinit(gpa); - var delta: std.Io.Writer.Allocating = .init(gpa); - defer delta.deinit(); - var line: [256]u8 = undefined; - for (0..60) |i| { - const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 }); - a.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); - delta.clearRetainingCapacity(); - try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer)); - peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq); - b.needs_frame = true; - _ = fa.reset(.retain_capacity); - _ = fb.reset(.retain_capacity); - const sa = try a.render(fa.allocator()); - const sb = try b.render(fb.allocator()); - const r = a.view().rects[0]; - // The body: below the pane's tag row. - for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { - const ca = sa.at(@intCast(x), @intCast(y)); - const cb = sb.at(@intCast(x), @intCast(y)); - if (!ca.visuallyEqual(cb)) { - std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() }); - return error.ReplicaDrawsDifferently; - } - }; - } -} - // ---- a pane of a kind, as a Shadow (architecture §16.5) ---- // // A replica's core has no code for a library's kind: such a pane is drawn @@ -1557,6 +1399,164 @@ pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Kind.Fr return true; } +test "a replica's screen is its authority's, cell for cell, as states are skipped, resized and fetched" { + const gpa = testing.allocator; + const io = testing.io; + const shell = try shellStream(gpa); + defer gpa.free(shell); + const tui = try tuiStream(gpa); + defer gpa.free(tui); + const yes = try yesStream(gpa, 30_000); + defer gpa.free(yes); + var fetched: u64 = 0; + var history: u64 = 0; + for (0..4) |seed| { + // A small scrollback, so it wraps (pruned at its oldest pages). + for ([_][]const u8{ shell, tui, yes }) |bytes| { + const st = soak(gpa, io, bytes, 80, 24, 64 * 1024, seed, seed != 0) catch |err| { + std.debug.print("soak seed {d} stream {d} bytes: {s}\n", .{ seed, bytes.len, @errorName(err) }); + return err; + }; + try testing.expect(st.deltas > 10); + fetched += st.fetched; + history += st.history_checked; + } + } + // The holes were fetched, and history rows compared, at all. + try testing.expect(fetched > 0 and history > 0); +} + +test "under a flood a delta is a screen of hashes: an unchanged row costs its address alone" { + const gpa = testing.allocator; + const s = try Soak.init(gpa, testing.io, 200, 60, 1 << 20, 1); + defer s.deinit(); + s.resizes = false; + s.drops = false; + const yes = try yesStream(gpa, 10_000); + defer gpa.free(yes); + var last: []u8 = &.{}; + defer gpa.free(last); + for (0..3) |_| { + s.stream.nextSlice(yes); + s.changes += 1; + try s.send(0); + try testing.expectEqual(@as(usize, 1), s.flight.items.len); + gpa.free(last); + last = try gpa.dupe(u8, s.flight.items[0].delta); + try s.land(); + } + // The last: 60 rows and the tail's 60, of hashes the replica holds, no + // blob; the header and counts around them. + const d = last; + const at = 4 + 4 + 1 + 4 + 8 + 2 + 2 + 1 + 1 + 1 + @sizeOf(KittyFlags) + 8 + 8 + 8 + 2 + "extra".len; + const nrows = std.mem.readInt(u16, d[at..][0..2], .little); + const tail = std.mem.readInt(u16, d[at + 2 + nrows * 8 ..][0..2], .little); + const blobs = std.mem.readInt(u16, d[at + 4 + (nrows + tail) * 8 ..][0..2], .little); + if (d.len >= (nrows + tail) * 8 + 128) std.debug.print("delta {d} bytes: {d} rows, {d} tail, {d} blobs\n", .{ d.len, nrows, tail, blobs }); + try testing.expectEqual(@as(u16, 0), blobs); + try testing.expect(d.len < (nrows + tail) * 8 + 128); + try testing.expect(s.rep.holes.items.len > 0); +} + +test "a reflow to fewer columns keeps every history row numbered at or past 0" { + const gpa = testing.allocator; + const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 3); + defer s.deinit(); + s.resizes = false; + s.drops = false; + // Lines of 69 columns scrolled into the history, then the screen + // narrowed so that each wraps in three: more rows above the last top + // than ever scrolled past it (a window client's font, 2026-10-30: the + // session's peer started afresh at `top - history`, which overflowed). + var line: [80]u8 = undefined; + for (0..200) |i| { + s.stream.nextSlice(try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i})); + s.changes += 1; + } + try s.send(0); + try s.land(); + try s.a.resize(gpa, .{ .cols = 30, .rows = 24 }); + s.changes += 1; + try s.send(0); + try s.land(); + try s.settle(); + try testing.expect(s.track.rows.top >= s.track.history); +} + +test "several deltas in flight land in order, and a peer at the bound waits for an acknowledgement" { + const gpa = testing.allocator; + const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 2); + defer s.deinit(); + s.resizes = false; + s.drops = false; + var line: [64]u8 = undefined; + for (0..bound + 5) |i| { + s.stream.nextSlice(try std.fmt.bufPrint(&line, "line {d}\r\n", .{i})); + s.changes += 1; + try s.send(1000); + } + // The bound's worth went; the rest wait, and are skipped. + try testing.expectEqual(@as(usize, bound), s.flight.items.len); + try s.land(); + try s.send(1000); + try testing.expectEqual(@as(usize, bound), s.flight.items.len); + try s.settle(); + try testing.expectEqual(@as(u64, 0), s.stats.refused); +} + +test "a replica's terminal pane draws as its authority's does" { + const pardes = @import("pardes.zig"); + const gpa = testing.allocator; + const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer a.deinit(); + const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer b.deinit(); + while (a.nextEffect()) |_| {} + while (b.nextEffect()) |_| {} + var fa = std.heap.ArenaAllocator.init(gpa); + defer fa.deinit(); + var fb = std.heap.ArenaAllocator.init(gpa); + defer fb.deinit(); + // Laid out once, so both panes have their size before the first delta. + _ = try a.render(fa.allocator()); + _ = try b.render(fb.allocator()); + const ta = &a.panes[0].?.terminal.?.vt; + const tb = &b.panes[0].?.terminal.?.vt; + var enc: Encoder = .init(gpa); + defer enc.deinit(); + var peer: Peer = .{}; + defer peer.deinit(gpa); + var tr: Track = .init(gpa); + defer tr.deinit(gpa, ta); + var rep: Replica = .{}; + defer rep.deinit(gpa); + var delta: std.Io.Writer.Allocating = .init(gpa); + defer delta.deinit(); + var line: [256]u8 = undefined; + for (0..60) |i| { + const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 }); + a.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); + delta.clearRetainingCapacity(); + try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer)); + peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq); + b.needs_frame = true; + _ = fa.reset(.retain_capacity); + _ = fb.reset(.retain_capacity); + const sa = try a.render(fa.allocator()); + const sb = try b.render(fb.allocator()); + const r = a.view().rects[0]; + // The body: below the pane's tag row. + for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { + const ca = sa.at(@intCast(x), @intCast(y)); + const cb = sb.at(@intCast(x), @intCast(y)); + if (!ca.visuallyEqual(cb)) { + std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() }); + return error.ReplicaDrawsDifferently; + } + }; + } +} + test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" { const gpa = std.testing.allocator; var cells: [2 * 3]Cell = @splat(std.mem.zeroes(Cell)); diff --git a/src/surface.zig b/src/surface.zig index 5bee28d7..9333a75e 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -54,21 +54,6 @@ pub const Cell = struct { } }; -test "cell visual equality ignores dead grapheme tail bytes" { - var a: Cell = .{ .default = false }; - var b = a; - a.text[0] = 'x'; - b.text[0] = 'x'; - a.text[4] = 'a'; - b.text[4] = 'b'; - try std.testing.expect(a.visuallyEqual(&b)); - b.style.bold = true; - try std.testing.expect(!a.visuallyEqual(&b)); - a.default = true; - b.default = true; - try std.testing.expect(a.visuallyEqual(&b)); -} - /// A rectangle in pixels. pub const RectPx = struct { x: u32 = 0, @@ -128,20 +113,6 @@ pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeom return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; } -test "native image contain keeps aspect, bounds, top-left, and small-image size" { - try std.testing.expectEqual(RectPx{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst); - try std.testing.expectEqual(RectPx{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst); - try std.testing.expectEqual(RectPx{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst); - try std.testing.expect(containGeometry(17, 9, 0, 40) == null); - - const odd = containGeometry(403, 211, 101, 47).?; - try std.testing.expectEqual(RectPx{ .w = 89, .h = 47 }, odd.dst); - try std.testing.expectEqual(RectPx{ .w = 403, .h = 211 }, odd.src); - // Nothing its backend contract cannot represent. - try std.testing.expect(containGeometry(0, 10, 20, 20) == null); - if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null); -} - /// A rectangle in the frame's cells. pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; @@ -210,14 +181,6 @@ pub const Placement = struct { } }; -test "a placement's key follows its pane, its page and the revision of its pixels, and nothing of where it goes" { - const first = Placement.keyOf(41, 7, 3); - try std.testing.expectEqual(first, Placement.keyOf(41, 7, 3)); - try std.testing.expect(first != Placement.keyOf(41, 8, 3)); - try std.testing.expect(first != Placement.keyOf(41, 7, 4)); - try std.testing.expect(first != Placement.keyOf(42, 7, 3)); -} - /// One part of the frame and where it is, placed once by `draw.place` /// before anything is painted: every painter and every shell reads the /// geometry here instead of working it out again. `rect` is in grid cells @@ -517,6 +480,43 @@ pub const Surface = struct { } }; +test "cell visual equality ignores dead grapheme tail bytes" { + var a: Cell = .{ .default = false }; + var b = a; + a.text[0] = 'x'; + b.text[0] = 'x'; + a.text[4] = 'a'; + b.text[4] = 'b'; + try std.testing.expect(a.visuallyEqual(&b)); + b.style.bold = true; + try std.testing.expect(!a.visuallyEqual(&b)); + a.default = true; + b.default = true; + try std.testing.expect(a.visuallyEqual(&b)); +} + +test "native image contain keeps aspect, bounds, top-left, and small-image size" { + try std.testing.expectEqual(RectPx{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst); + try std.testing.expectEqual(RectPx{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst); + try std.testing.expectEqual(RectPx{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst); + try std.testing.expect(containGeometry(17, 9, 0, 40) == null); + + const odd = containGeometry(403, 211, 101, 47).?; + try std.testing.expectEqual(RectPx{ .w = 89, .h = 47 }, odd.dst); + try std.testing.expectEqual(RectPx{ .w = 403, .h = 211 }, odd.src); + // Nothing its backend contract cannot represent. + try std.testing.expect(containGeometry(0, 10, 20, 20) == null); + if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null); +} + +test "a placement's key follows its pane, its page and the revision of its pixels, and nothing of where it goes" { + const first = Placement.keyOf(41, 7, 3); + try std.testing.expectEqual(first, Placement.keyOf(41, 7, 3)); + try std.testing.expect(first != Placement.keyOf(41, 8, 3)); + try std.testing.expect(first != Placement.keyOf(41, 7, 4)); + try std.testing.expect(first != Placement.keyOf(42, 7, 3)); +} + test "surface print expands configured tabs and normalizes other controls" { const tab_cells: usize = @as(usize, config.tab_width) * 2; const replacement_cells = 5; diff --git a/src/syntax.zig b/src/syntax.zig index 753b11b1..08b26096 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -7,10 +7,6 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -test { - _ = diff; -} - pub const enabled = config.syntax_highlighting; const zig_grammar = config.syntax_zig_grammar; const minimal_grammars = config.syntax_minimal_grammars; @@ -622,22 +618,6 @@ pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, obje return s; } -test "every vendored textobject query compiles against its grammar" { - if (!enabled) return; - var failed: usize = 0; - for (&specs) |*spec| { - if (spec.objects_src.len == 0) continue; - var error_offset: u32 = 0; - const q = ts.Query.create(spec.language(), spec.objects_src, &error_offset) catch { - std.debug.print("textobjects for {s} do not compile (offset {d})\n", .{ spec.name, error_offset }); - failed += 1; - continue; - }; - q.destroy(); - } - try std.testing.expectEqual(@as(usize, 0), failed); -} - /// Owned source analysis. Both slices use the allocator passed to analyzeSource. /// The parsed tree is released before returning; callers can cache this result. pub const SourceAnalysis = struct { @@ -814,89 +794,6 @@ fn paintTree(styles: []u8, source: []const u8, selected: Selected, tree: *ts.Tre } } -test "syntax context nested Zig containers and multiline function signatures" { - if (!enabled) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const source = - "pub const Outer = struct {\n" ++ - " const Inner = struct {\n" ++ - " pub fn run(\n" ++ - " value: u32,\n" ++ - " ) void {\n" ++ - " const ignored = .{\n" ++ - " value,\n" ++ - " };\n" ++ - " }\n" ++ - " };\n" ++ - "};\n"; - const declarations = try contextDeclarations(gpa, "nested.zig", source); - defer gpa.free(declarations); - try std.testing.expectEqual(@as(usize, 3), declarations.len); - try std.testing.expectEqual(@as(usize, 0), declarations[0].start_line); - try std.testing.expectEqual(@as(usize, 10), declarations[0].end_line); - try std.testing.expectEqual(@as(usize, 1), declarations[1].start_line); - try std.testing.expectEqual(@as(usize, 2), declarations[2].start_line); - try std.testing.expectEqual(@as(usize, 4), declarations[2].header_end_line); - try std.testing.expectEqual(@as(usize, 8), declarations[2].end_line); - try std.testing.expectEqualStrings(" pub fn run(\n value: u32,\n ) void {", source[declarations[2].start_byte..declarations[2].header_end_byte]); - const unsupported = try contextDeclarations(gpa, "notes.unknown", source); - defer gpa.free(unsupported); - try std.testing.expectEqual(@as(usize, 0), unsupported.len); -} - -test "syntax context Python class and function body excludes first statement" { - if (!enabled or !full_grammars) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const source = "class Outer:\n def run(\n self, value,\n ):\n return value\n"; - const declarations = try contextDeclarations(gpa, "nested.py", source); - defer gpa.free(declarations); - try std.testing.expectEqual(@as(usize, 2), declarations.len); - try std.testing.expectEqual(@as(usize, 0), declarations[0].header_end_line); - try std.testing.expectEqual(@as(usize, 3), declarations[1].header_end_line); -} - -test "syntax context multiline bindings and C++ namespaces preserve declaration starts" { - if (!enabled) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const zig_source = "const Outer =\n struct {\n field: u8,\n };\n"; - const zig_declarations = try contextDeclarations(gpa, "nested.zig", zig_source); - defer gpa.free(zig_declarations); - try std.testing.expectEqual(@as(usize, 1), zig_declarations.len); - try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line); - try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line); - if (!minimal_grammars and !full_grammars) return; - const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n"; - const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source); - defer gpa.free(cpp_declarations); - try std.testing.expectEqual(@as(usize, 3), cpp_declarations.len); - for (cpp_declarations, 0..) |declaration, row| { - try std.testing.expectEqual(row, declaration.start_line); - try std.testing.expectEqual(row, declaration.header_end_line); - } -} - -test "syntax context Rust modules impls and methods remain nested" { - if (!enabled or !full_grammars) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const source = "mod outer {\n impl Example {\n fn run(&self) {\n work();\n }\n }\n}\n"; - const declarations = try contextDeclarations(gpa, "nested.rs", source); - defer gpa.free(declarations); - try std.testing.expectEqual(@as(usize, 3), declarations.len); - for (declarations, 0..) |declaration, row| { - try std.testing.expectEqual(row, declaration.start_line); - try std.testing.expectEqual(row, declaration.header_end_line); - try std.testing.expectEqual(@as(usize, 6) - row, declaration.end_line); - } -} - pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byte_raw: usize, end_byte_raw: usize) ![]u8 { const tz = tracy.zone(@src(), "highlightLocations"); defer tz.end(); @@ -1041,46 +938,6 @@ fn codeAfterLocation(line: []const u8) ?struct { path: []const u8, at: usize, te return .{ .path = target.path, .at = at, .text = line[at..] }; } -test "syntax formatted locations color hidden context and preserve multiline source" { - if (!enabled or (!minimal_grammars and !full_grammars)) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const first = "a path.c:1 \t/* open"; - const second = " \t| comment body"; - const third = "a path.c:3 \t*/ int value = 42;"; - const content = first ++ "\n" ++ second ++ "\n" ++ third ++ "\n"; - const path = @constCast("a path.c"); - const rows = [_]locations.Row{ - .{ .kind = .match, .path = path, .code_start = "a path.c:1 \t".len, .location_end = 0, .at = .{ .line = 1 } }, - .{ .kind = .context, .path = path, .code_start = " \t| ".len, .location_end = 0, .at = .{ .line = 2 } }, - .{ .kind = .match, .path = path, .code_start = "a path.c:3 \t".len, .location_end = 0, .at = .{ .line = 3 } }, - }; - const styles = try highlightLocationRows(gpa, content, &rows); - defer gpa.free(styles); - const body = std.mem.indexOf(u8, content, "comment body").?; - try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]); - try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]); - const number = std.mem.indexOf(u8, content, "42").?; - try std.testing.expectEqual(@backingInt(Syn.number), styles[number]); - try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); -} - -test "syntax formatted locations separate alignment from Markdown indentation" { - if (!enabled or !full_grammars) return; - const gpa = std.testing.allocator; - start(gpa); - defer stop(); - const content = "short.md:1 \t# Heading\n" ++ "longer path.md:5 \t # Code\n"; - const rows = [_]locations.Row{ - .{ .kind = .match, .path = @constCast("short.md"), .code_start = "short.md:1 \t".len, .location_end = 0, .at = .{ .line = 1 } }, - .{ .kind = .match, .path = @constCast("longer path.md"), .code_start = "longer path.md:5 \t".len, .location_end = 0, .at = .{ .line = 5 } }, - }; - const styles = try highlightLocationRows(gpa, content, &rows); - defer gpa.free(styles); - try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); - try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); -} fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void { const kind = node.kind(); if (markdown and std.mem.eql(u8, kind, "inline")) { @@ -1394,6 +1251,154 @@ fn codeStart(line: []const u8, kind: diff.Kind) usize { }; } +fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { + return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits)); +} + +test { + _ = diff; +} + +test "every vendored textobject query compiles against its grammar" { + if (!enabled) return; + var failed: usize = 0; + for (&specs) |*spec| { + if (spec.objects_src.len == 0) continue; + var error_offset: u32 = 0; + const q = ts.Query.create(spec.language(), spec.objects_src, &error_offset) catch { + std.debug.print("textobjects for {s} do not compile (offset {d})\n", .{ spec.name, error_offset }); + failed += 1; + continue; + }; + q.destroy(); + } + try std.testing.expectEqual(@as(usize, 0), failed); +} + +test "syntax context nested Zig containers and multiline function signatures" { + if (!enabled) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const source = + "pub const Outer = struct {\n" ++ + " const Inner = struct {\n" ++ + " pub fn run(\n" ++ + " value: u32,\n" ++ + " ) void {\n" ++ + " const ignored = .{\n" ++ + " value,\n" ++ + " };\n" ++ + " }\n" ++ + " };\n" ++ + "};\n"; + const declarations = try contextDeclarations(gpa, "nested.zig", source); + defer gpa.free(declarations); + try std.testing.expectEqual(@as(usize, 3), declarations.len); + try std.testing.expectEqual(@as(usize, 0), declarations[0].start_line); + try std.testing.expectEqual(@as(usize, 10), declarations[0].end_line); + try std.testing.expectEqual(@as(usize, 1), declarations[1].start_line); + try std.testing.expectEqual(@as(usize, 2), declarations[2].start_line); + try std.testing.expectEqual(@as(usize, 4), declarations[2].header_end_line); + try std.testing.expectEqual(@as(usize, 8), declarations[2].end_line); + try std.testing.expectEqualStrings(" pub fn run(\n value: u32,\n ) void {", source[declarations[2].start_byte..declarations[2].header_end_byte]); + const unsupported = try contextDeclarations(gpa, "notes.unknown", source); + defer gpa.free(unsupported); + try std.testing.expectEqual(@as(usize, 0), unsupported.len); +} + +test "syntax context Python class and function body excludes first statement" { + if (!enabled or !full_grammars) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const source = "class Outer:\n def run(\n self, value,\n ):\n return value\n"; + const declarations = try contextDeclarations(gpa, "nested.py", source); + defer gpa.free(declarations); + try std.testing.expectEqual(@as(usize, 2), declarations.len); + try std.testing.expectEqual(@as(usize, 0), declarations[0].header_end_line); + try std.testing.expectEqual(@as(usize, 3), declarations[1].header_end_line); +} + +test "syntax context multiline bindings and C++ namespaces preserve declaration starts" { + if (!enabled) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const zig_source = "const Outer =\n struct {\n field: u8,\n };\n"; + const zig_declarations = try contextDeclarations(gpa, "nested.zig", zig_source); + defer gpa.free(zig_declarations); + try std.testing.expectEqual(@as(usize, 1), zig_declarations.len); + try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line); + try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line); + if (!minimal_grammars and !full_grammars) return; + const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n"; + const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source); + defer gpa.free(cpp_declarations); + try std.testing.expectEqual(@as(usize, 3), cpp_declarations.len); + for (cpp_declarations, 0..) |declaration, row| { + try std.testing.expectEqual(row, declaration.start_line); + try std.testing.expectEqual(row, declaration.header_end_line); + } +} + +test "syntax context Rust modules impls and methods remain nested" { + if (!enabled or !full_grammars) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const source = "mod outer {\n impl Example {\n fn run(&self) {\n work();\n }\n }\n}\n"; + const declarations = try contextDeclarations(gpa, "nested.rs", source); + defer gpa.free(declarations); + try std.testing.expectEqual(@as(usize, 3), declarations.len); + for (declarations, 0..) |declaration, row| { + try std.testing.expectEqual(row, declaration.start_line); + try std.testing.expectEqual(row, declaration.header_end_line); + try std.testing.expectEqual(@as(usize, 6) - row, declaration.end_line); + } +} + +test "syntax formatted locations color hidden context and preserve multiline source" { + if (!enabled or (!minimal_grammars and !full_grammars)) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const first = "a path.c:1 \t/* open"; + const second = " \t| comment body"; + const third = "a path.c:3 \t*/ int value = 42;"; + const content = first ++ "\n" ++ second ++ "\n" ++ third ++ "\n"; + const path = @constCast("a path.c"); + const rows = [_]locations.Row{ + .{ .kind = .match, .path = path, .code_start = "a path.c:1 \t".len, .location_end = 0, .at = .{ .line = 1 } }, + .{ .kind = .context, .path = path, .code_start = " \t| ".len, .location_end = 0, .at = .{ .line = 2 } }, + .{ .kind = .match, .path = path, .code_start = "a path.c:3 \t".len, .location_end = 0, .at = .{ .line = 3 } }, + }; + const styles = try highlightLocationRows(gpa, content, &rows); + defer gpa.free(styles); + const body = std.mem.indexOf(u8, content, "comment body").?; + try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]); + const number = std.mem.indexOf(u8, content, "42").?; + try std.testing.expectEqual(@backingInt(Syn.number), styles[number]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); +} + +test "syntax formatted locations separate alignment from Markdown indentation" { + if (!enabled or !full_grammars) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const content = "short.md:1 \t# Heading\n" ++ "longer path.md:5 \t # Code\n"; + const rows = [_]locations.Row{ + .{ .kind = .match, .path = @constCast("short.md"), .code_start = "short.md:1 \t".len, .location_end = 0, .at = .{ .line = 1 } }, + .{ .kind = .match, .path = @constCast("longer path.md"), .code_start = "longer path.md:5 \t".len, .location_end = 0, .at = .{ .line = 5 } }, + }; + const styles = try highlightLocationRows(gpa, content, &rows); + defer gpa.free(styles); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); +} + test "syntax a results row is coloured by the file its location names" { if (!enabled) return; start(std.testing.allocator); @@ -1630,10 +1635,6 @@ test "syntax highlightDiff colors unified diff lines by prefix" { try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0); } -fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { - return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits)); -} - test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { if (!enabled) return; start(std.testing.allocator); diff --git a/src/tagline.zig b/src/tagline.zig index b9abf5f0..a7438be3 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -449,6 +449,40 @@ pub fn workspaceBlank(p: *Pardes, col: u16, row: u16, tag_hit: ?pardes.TagHit) b return at >= panes.File.displayWidth(modal.lineSlice(text, 0)) + 2; } +/// Column and workspace tags are one line, as acme's: a newline typed, +/// pasted or restored from a dump into one becomes a space, the caret and +/// the selection kept on the same characters. +pub fn flattenHeaders(p: *Pardes) void { + for (p.view().col_tags[0..p.view().ncol]) |*t| flatten(t); + flatten(&p.global_tag); +} + +fn flatten(t: *Text) void { + const own = t.own orelse return; + if (std.mem.indexOfScalar(u8, own, '\n') == null) return; + const cur = modal.offsetAt(own, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + const anchor = modal.offsetAt(own, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); + std.mem.replaceScalar(u8, own, '\n', ' '); + t.cur_row = 0; + t.cur_col = @intCast(cur); + t.vsel.row = 0; + t.vsel.col = @intCast(anchor); + t.nsel = 0; +} + +const WordBounds = struct { lo: usize, hi: usize }; + +/// The space-delimited word covering `col` in `str` (a header's click and +/// hover), null on a space or past the end. +pub fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { + if (col >= str.len or str[col] == ' ') return null; + var lo: usize = col; + while (lo > 0 and str[lo - 1] != ' ') lo -= 1; + var hi: usize = col; + while (hi < str.len and str[hi] != ' ') hi += 1; + return .{ .lo = lo, .hi = hi }; +} + test "the workspace tag is blank left of its text and past its end, and nowhere else" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12, .tty_only = true }); defer p.deinit(); @@ -474,27 +508,6 @@ test "the workspace tag is blank left of its text and past its end, and nowhere try std.testing.expect(!workspaceBlank(p, 79, 0, null)); } -/// Column and workspace tags are one line, as acme's: a newline typed, -/// pasted or restored from a dump into one becomes a space, the caret and -/// the selection kept on the same characters. -pub fn flattenHeaders(p: *Pardes) void { - for (p.view().col_tags[0..p.view().ncol]) |*t| flatten(t); - flatten(&p.global_tag); -} - -fn flatten(t: *Text) void { - const own = t.own orelse return; - if (std.mem.indexOfScalar(u8, own, '\n') == null) return; - const cur = modal.offsetAt(own, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); - const anchor = modal.offsetAt(own, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); - std.mem.replaceScalar(u8, own, '\n', ' '); - t.cur_row = 0; - t.cur_col = @intCast(cur); - t.vsel.row = 0; - t.vsel.col = @intCast(anchor); - t.nsel = 0; -} - test "a column or workspace tag is one line: a newline in it is a space" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 12, .tty_only = true }); defer p.deinit(); @@ -520,16 +533,3 @@ test "a pane tag wraps a long line onto rows, and offsets map both ways" { try std.testing.expectEqual(@as(usize, 10), shown.toReal(11)); // the 'e' of Del try std.testing.expectEqual(@as(usize, 11), shown.fromReal(10)); } - -const WordBounds = struct { lo: usize, hi: usize }; - -/// The space-delimited word covering `col` in `str` (a header's click and -/// hover), null on a space or past the end. -pub fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { - if (col >= str.len or str[col] == ' ') return null; - var lo: usize = col; - while (lo > 0 and str[lo - 1] != ' ') lo -= 1; - var hi: usize = col; - while (hi < str.len and str[hi] != ' ') hi += 1; - return .{ .lo = lo, .hi = hi }; -} diff --git a/src/terminal.zig b/src/terminal.zig index 16ffb34b..d8f279dc 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -565,7 +565,7 @@ pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { const m = &state.stream.handler; var w: std.Io.Writer = .fixed(buf); - w.writeByte(@intFromEnum(m.phase)) catch unreachable; + w.writeByte(@backingInt(m.phase)) catch unreachable; inline for (.{ m.started, m.prompts, m.declined }) |n| w.writeInt(u32, n, .little) catch unreachable; w.writeAll(&.{ @intFromBool(m.continuation), @intFromBool(m.lost) }) catch unreachable; w.writeInt(u32, if (m.finished) |f| f.seq else std.math.maxInt(u32), .little) catch unreachable; @@ -577,7 +577,7 @@ pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { pub fn takeMarks(state: *State, bytes: []const u8) void { if (bytes.len != marks_len) return; const m = &state.stream.handler; - m.phase = @enumFromInt(bytes[0]); + m.phase = @fromBackingInt(@intCast(bytes[0])); m.started = std.mem.readInt(u32, bytes[1..5], .little); m.prompts = std.mem.readInt(u32, bytes[5..9], .little); m.declined = std.mem.readInt(u32, bytes[9..13], .little); @@ -949,188 +949,6 @@ fn ingest(pane: *Pane, bytes: []const u8) void { pane.terminal.?.changes +%= 1; } -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawResize(buf, a, n, ra); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - self.child.rawFree(buf, a, ra); - } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expect(pane.terminal.?.resize_to == null); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer deinitEmulator(pane, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expect(!bracketedPaste(pane)); - try std.testing.expect(!reportsMouse(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, 80, 24); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - replies += 1; - } - try std.testing.expectEqual(@as(usize, 1), replies); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); -} - -test "a terminal's dump restores the cells it drew, its history and where its view was" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - for (0..30) |i| { - var line: [16]u8 = undefined; - feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); - } - scrollGrid(pane, -5); - const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); - defer gpa.free(bytes); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const state = try gpa.create(State); - defer gpa.destroy(state); - state.* = try pardes.walk.load(State, gpa, bytes, null); - defer { - state.stream.deinit(); - state.vt.deinit(gpa); - } - try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); - try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - /// What a pane says when a position kept over its terminal's rows could /// not follow the output (no memory for its pin), so it was reset. const positions_lost = "terminal edit position reset: out of memory"; @@ -1434,42 +1252,6 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) bool { return failed; } -test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - feedOutput(p, pane, "one\r\ntwo\r\n"); - // More positions than the emulator's pins have room for: following them - // through the output needs memory, and there is none. - try std.testing.expect(pane.body.reserveSels()); - for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; - pane.body.nsel = 8; - failing.fail_index = failing.alloc_index; - feedOutput(p, pane, "three\r\n"); - failing.fail_index = std.math.maxInt(usize); - try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualStrings(positions_lost, pane.msg[0..pane.msg_len]); - const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(positions_lost, logged.slice()); -} - -test "raw terminal output needs no position tracking allocations" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - feedOutput(p, pane, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - /// A full-screen program has the emulator on its alternate screen. pub fn onAlternateScreen(pane: *const Pane) bool { const state = pane.terminal orelse return false; @@ -1834,17 +1616,6 @@ pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { return c.rows; } -test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - try std.testing.expect(pane.terminal != null); - _ = try shellRows(p, pane); - // A pane's teardown drops its entry; the rows stay until the sweep. - p.shell_rows.dropPane(pane); - _ = try shellRows(p, pane); -} - /// The full modal motion surface: shell history with the live edit overlay /// spliced into the rows it covers. pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { @@ -1976,7 +1747,6 @@ pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { overlay.text = new; } - /// Set while a frame is drawn: what it reads is no step's. pub var drawing = false; @@ -2400,7 +2170,7 @@ fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghost // cast takes one to the other (cellStyle, pager.zig). comptime { for (@typeInfo(@FieldType(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| - if (@intFromEnum(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); + if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); } fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { @@ -2415,7 +2185,7 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor .reverse = style.flags.inverse, .invisible = style.flags.invisible, .strikethrough = style.flags.strikethrough, - .ul = @enumFromInt(@intFromEnum(style.flags.underline)), + .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), }; if (filtered == null) switch (ci.cell.content_tag) { .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), @@ -2604,31 +2374,446 @@ fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { return @intCast(dr * dr + dg * dg + db * db); } -test "the luminance table answers exactly what ghostty computes" { - for (0..256) |i| { - const c: u8 = @intCast(i); - const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; - try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); - } - // Channel weights are asymmetric, so a grey ramp alone would not catch a - // transposed coefficient. The palette is what the tables enumerate. - for (GColor.default) |candidate| { - try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); - for (GColor.default) |page| { - try std.testing.expectEqual( - candidate.contrast(page), - contrastOf(luminanceOf(candidate), luminanceOf(page)), - ); - } - } +pub fn palColor(p: *Pardes, idx: u8) pardes.Color { + if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; + return .{ .index = idx }; } -test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { - const testing = std.testing; - // Raw index assertions require a theme that inherits the ANSI palette. - const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} +fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { + return switch (color) { + .none => blk: { + const t = if (is_bg) p.theme().bg else p.theme().fg; + break :blk if (t) |c| .{ .rgb = c } else .default; + }, + .palette => |idx| palColor(p, idx), + .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, + }; +} + +/// executing at a prompt with typed text below it: pad the output area +/// with newlines so the command's output doesn't overwrite the buffer +pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { + // Nothing to pad away from: with no emulator there is no prompt and no + // child whose output could land on top of the edit buffer. + const pane = p.panes[id] orelse return; + const o = pane.ovl orelse return; + if (!pane.isTerminal()) return; + const state = pane.terminal orelse return; + if (!state.vt.cursorIsAtPrompt()) return; + // the buffer's LAST surface row: its lines may outnumber the shell + // rows it covers, and it is the bottom one output must clear + const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; + const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); + const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); + const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); + var i: i32 = 0; + while (i < pad) : (i += 1) p.emitWrite(id, "\r"); +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + pane.body.remember(p.gpa, pane.ovl); +} + +/// Undo (back) or redo one step of the edit overlay. +pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) void { + const to = pane.body.step(p.gpa, pane.ovl, back) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = to.ovl; + pane.ensureCursorVisible(); +} + +fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + // A cut answer is worse than none: the program would read the start of + // a sequence and wait, or misparse what follows. + if (data.len > room) { + state.reply_dropped +|= 1; + return; + } + @memcpy(state.reply[state.reply_len..][0..data.len], data); + state.reply_len += @intCast(data.len); +} + +fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { + return .{}; +} + +/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a +/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. +fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { + const t = handler.terminal; + if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; + return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; +} + +/// The emulator's size in pixels follows the shell's cells: kitty graphics +/// placements are sized by it, and CSI 14/16 t report it. +fn syncPixels(p: *const Pardes, pane: *Pane) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + const vt = &state.vt; + vt.width_px = @as(u32, vt.cols) * p.view().cell_pixels.w; + vt.height_px = @as(u32, vt.rows) * p.view().cell_pixels.h; +} + +/// When the pane's next kitty animation frame is due (ms on the core's +/// clock), as its last drawn frame left it; null when nothing plays. +pub fn animationDueMs(pane: *const Pane) ?u64 { + if (comptime !images_enabled) return null; + const state = pane.terminal orelse return null; + return state.images.animation_due_ms; +} + +/// The Petscii builtin on a terminal: its kitty graphics as glyph art, +/// or back to pixels where the shell draws pixels. +pub fn togglePetscii(pane: *Pane) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + state.images.petscii = !state.images.petscii; +} + +/// Whether the pane draws its kitty graphics as glyph art by choice; null +/// for a pane with no emulator. +pub fn petscii(pane: *const Pane) ?bool { + if (comptime !images_enabled) return null; + const state = pane.terminal orelse return null; + return state.images.petscii; +} + +/// Whether the screen showing holds any kitty graphics image. +pub fn hasImages(pane: *const Pane) bool { + if (comptime !images_enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active.kitty_images.images.count() > 0; +} + +/// Draw the pane's kitty graphics images over its body rows (after the +/// rows and their colours: placeholder cells are blanked here). +pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + syncPixels(p, pane); + // A body taller than this draws its images on the rows that fit. + var rows_of: [1024]?u16 = undefined; + const vp_rows: usize = @min(scrollbar(pane).len, rows_of.len); + @memset(rows_of[0..vp_rows], null); + var any_placeholder = false; + var walk: BodyWalk = .init(pane); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + const vi = switch (row) { + .grid => |v| v, + .edit => continue, + }; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const flags = row_pin.rowAndCell().row; + // A prompt row outside tty mode is cut or hidden: its columns are + // not the grid's. + if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; + any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; + rows_of[@intCast(vi)] = vr; + } + // Nothing to draw, no placeholder to blank and nothing cached to let + // go: the common case costs the rows' flags. + if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; + state.images.draw(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); +} + +/// Every byte the core wrote to each pane's pty since the last call, `\n` +/// between panes' shares: "0:\n1:\n" for panes that got any. +fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); + defer for (&per) |*b| b.deinit(p.gpa); + while (p.nextEffect()) |effect| { + if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); + } + for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); + return out.items; +} + +/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the +/// right, with the rest of the control data `extra` (`c=2,r=1` places it +/// over two cells). +inline fn kittyTransmit(comptime extra: []const u8) []const u8 { + return comptime blk: { + const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; + const pixels = row ++ row; + var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; + const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; + break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; + }; +} + +fn imagePlaces(s: *const Surface) []const pardes.Placement { + return s.placements.items; +} + +/// `n` line breaks: enough of them push the screen's rows into history. +fn lineBreaks(comptime n: usize) [2 * n]u8 { + var out: [2 * n]u8 = undefined; + for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; + return out; +} + +test "replay ownership is terminal-only and construction rolls back on allocation failure" { + const Case = struct { + fn run(gpa: std.mem.Allocator, terminal: bool) !void { + const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqual(terminal, pane.terminal != null); + } + }; + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); +} + +test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { + // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field + // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). + const Filling = struct { + child: std.mem.Allocator, + fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + const ptr = self.child.rawAlloc(len, a, ra) orelse return null; + @memset(ptr[0..len], 0xAA); + return ptr; + } + fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawResize(buf, a, n, ra); + } + fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawRemap(buf, a, n, ra); + } + fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + self.child.rawFree(buf, a, ra); + } + const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; + }; + var filling: Filling = .{ .child = std.testing.allocator }; + const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expect(pane.terminal.?.resize_to == null); +} + +test "document construction allocates only the pane and has inert terminal defaults" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const allocator = failing.allocator(); + const pane = try createDoc(allocator, 40, 12); + defer allocator.destroy(pane); + defer deinitEmulator(pane, allocator); + try std.testing.expect(pane.terminal == null); + try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); + try std.testing.expectEqual(@as(usize, 0), failing.resize_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expect(!bracketedPaste(pane)); + try std.testing.expect(!reportsMouse(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, 80, 24); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + const state = pane.terminal.?; + try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); + while (p.nextEffect()) |effect| { + if (effect == .write) return error.PrematureTerminalReply; + } + p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); + var replies: usize = 0; + while (p.nextEffect()) |effect| { + if (effect != .write) continue; + try std.testing.expectEqual(@as(u8, 0), effect.write.pane); + try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); + replies += 1; + } + try std.testing.expectEqual(@as(usize, 1), replies); + try std.testing.expectEqual(@as(u16, 0), state.reply_len); +} + +test "a terminal's dump restores the cells it drew, its history and where its view was" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + for (0..30) |i| { + var line: [16]u8 = undefined; + feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); + } + scrollGrid(pane, -5); + const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); + defer gpa.free(bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const state = try gpa.create(State); + defer gpa.destroy(state); + state.* = try pardes.walk.load(State, gpa, bytes, null); + defer { + state.stream.deinit(); + state.vt.deinit(gpa); + } + try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); + try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); +} + +test "a restored command pane comes back finished, its command not run again" { + if (comptime pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const cmd = p.freeSlot().?; + _ = try panes.newCommand(p, cmd, "/tmp", "make test"); + feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); + defer restored.deinit(); + var spawns: usize = 0; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => spawns += 1, + else => {}, + }; + try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command + const again = for (restored.panes) |slot| { + if (slot) |pane| if (pane.command != null) break pane; + } else return error.CommandPaneLost; + try std.testing.expectEqualStrings("make test", again.command.?); + try std.testing.expect(again.command_done); + try std.testing.expectEqual(@as(?u8, 2), again.command_status); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); +} + +test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "old output\r\n$ ls\r\n"); + try pane.setOwnedCwd("/tmp"); + pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + defer restored.deinit(); + var spawned = false; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), + else => {}, + }; + try std.testing.expect(spawned); + const again = restored.panes[0].?; + try std.testing.expectEqualStrings("bash", again.shell.?); + try std.testing.expect(again.command == null); + try std.testing.expectEqual(.spawn, again.pending_command.wait); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; + const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; + try std.testing.expect(old_at < mark_at); +} + +test "a position that cannot follow the output for want of memory is said on the message row, and logged" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + feedOutput(p, pane, "one\r\ntwo\r\n"); + // More positions than the emulator's pins have room for: following them + // through the output needs memory, and there is none. + try std.testing.expect(pane.body.reserveSels()); + for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; + pane.body.nsel = 8; + failing.fail_index = failing.alloc_index; + feedOutput(p, pane, "three\r\n"); + failing.fail_index = std.math.maxInt(usize); + try std.testing.expect(failing.has_induced_failure); + try std.testing.expectEqualStrings(positions_lost, pane.msg[0..pane.msg_len]); + const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; + try std.testing.expectEqualStrings(positions_lost, logged.slice()); +} + +test "raw terminal output needs no position tracking allocations" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + feedOutput(p, pane, "warm"); + const allocations = failing.alloc_index; + failing.fail_index = allocations; + const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); + feedOutput(p, pane, " output"); + try std.testing.expectEqual(allocations, failing.alloc_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); +} + +test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expect(pane.terminal != null); + _ = try shellRows(p, pane); + // A pane's teardown drops its entry; the rows stay until the sweep. + p.shell_rows.dropPane(pane); + _ = try shellRows(p, pane); +} + +test "the luminance table answers exactly what ghostty computes" { + for (0..256) |i| { + const c: u8 = @intCast(i); + const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; + try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); + } + // Channel weights are asymmetric, so a grey ramp alone would not catch a + // transposed coefficient. The palette is what the tables enumerate. + for (GColor.default) |candidate| { + try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); + for (GColor.default) |page| { + try std.testing.expectEqual( + candidate.contrast(page), + contrastOf(luminanceOf(candidate), luminanceOf(page)), + ); + } + } +} + +test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { + const testing = std.testing; + // Raw index assertions require a theme that inherits the ANSI palette. + const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tag_expanded = false; // a one-row tag keeps this small screen's rows p.sync(); @@ -2985,168 +3170,6 @@ test "a prompt row hidden end to end paints nothing at all" { try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); } -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { - return switch (color) { - .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; - break :blk if (t) |c| .{ .rgb = c } else .default; - }, - .palette => |idx| palColor(p, idx), - .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, - }; -} - -/// executing at a prompt with typed text below it: pad the output area -/// with newlines so the command's output doesn't overwrite the buffer -pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { - // Nothing to pad away from: with no emulator there is no prompt and no - // child whose output could land on top of the edit buffer. - const pane = p.panes[id] orelse return; - const o = pane.ovl orelse return; - if (!pane.isTerminal()) return; - const state = pane.terminal orelse return; - if (!state.vt.cursorIsAtPrompt()) return; - // the buffer's LAST surface row: its lines may outnumber the shell - // rows it covers, and it is the bottom one output must clear - const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); - const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); - const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); - var i: i32 = 0; - while (i < pad) : (i += 1) p.emitWrite(id, "\r"); -} - -pub fn pushUndo(p: *Pardes, pane: *Pane) void { - pane.body.remember(p.gpa, pane.ovl); -} - -/// Undo (back) or redo one step of the edit overlay. -pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) void { - const to = pane.body.step(p.gpa, pane.ovl, back) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = to.ovl; - pane.ensureCursorVisible(); -} - -fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - // A cut answer is worse than none: the program would read the start of - // a sequence and wait, or misparse what follows. - if (data.len > room) { - state.reply_dropped +|= 1; - return; - } - @memcpy(state.reply[state.reply_len..][0..data.len], data); - state.reply_len += @intCast(data.len); -} - -fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { - return .{}; -} - -/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a -/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. -fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { - const t = handler.terminal; - if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; - return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; -} - -/// The emulator's size in pixels follows the shell's cells: kitty graphics -/// placements are sized by it, and CSI 14/16 t report it. -fn syncPixels(p: *const Pardes, pane: *Pane) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const vt = &state.vt; - vt.width_px = @as(u32, vt.cols) * p.view().cell_pixels.w; - vt.height_px = @as(u32, vt.rows) * p.view().cell_pixels.h; -} - -/// When the pane's next kitty animation frame is due (ms on the core's -/// clock), as its last drawn frame left it; null when nothing plays. -pub fn animationDueMs(pane: *const Pane) ?u64 { - if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; - return state.images.animation_due_ms; -} - -/// The Petscii builtin on a terminal: its kitty graphics as glyph art, -/// or back to pixels where the shell draws pixels. -pub fn togglePetscii(pane: *Pane) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - state.images.petscii = !state.images.petscii; -} - -/// Whether the pane draws its kitty graphics as glyph art by choice; null -/// for a pane with no emulator. -pub fn petscii(pane: *const Pane) ?bool { - if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; - return state.images.petscii; -} - -/// Whether the screen showing holds any kitty graphics image. -pub fn hasImages(pane: *const Pane) bool { - if (comptime !images_enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active.kitty_images.images.count() > 0; -} - -/// Draw the pane's kitty graphics images over its body rows (after the -/// rows and their colours: placeholder cells are blanked here). -pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - syncPixels(p, pane); - // A body taller than this draws its images on the rows that fit. - var rows_of: [1024]?u16 = undefined; - const vp_rows: usize = @min(scrollbar(pane).len, rows_of.len); - @memset(rows_of[0..vp_rows], null); - var any_placeholder = false; - var walk: BodyWalk = .init(pane); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - const vi = switch (row) { - .grid => |v| v, - .edit => continue, - }; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const flags = row_pin.rowAndCell().row; - // A prompt row outside tty mode is cut or hidden: its columns are - // not the grid's. - if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; - any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; - rows_of[@intCast(vi)] = vr; - } - // Nothing to draw, no placeholder to blank and nothing cached to let - // go: the common case costs the rows' flags. - if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; - state.images.draw(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); -} - -/// Every byte the core wrote to each pane's pty since the last call, `\n` -/// between panes' shares: "0:\n1:\n" for panes that got any. -fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); - defer for (&per) |*b| b.deinit(p.gpa); - while (p.nextEffect()) |effect| { - if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); - } - for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); - return out.items; -} - test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); @@ -3185,23 +3208,6 @@ test "a program that asked for focus reports hears CSI I and CSI O as its pane t try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); } -/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the -/// right, with the rest of the control data `extra` (`c=2,r=1` places it -/// over two cells). -inline fn kittyTransmit(comptime extra: []const u8) []const u8 { - return comptime blk: { - const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; - const pixels = row ++ row; - var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; - const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; - break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; - }; -} - -fn imagePlaces(s: *const Surface) []const pardes.Placement { - return s.placements.items; -} - test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; @@ -3249,13 +3255,6 @@ test "a terminal's kitty graphics image is drawn where its program placed it, an try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); } -/// `n` line breaks: enough of them push the screen's rows into history. -fn lineBreaks(comptime n: usize) [2 * n]u8 { - var out: [2 * n]u8 = undefined; - for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; - return out; -} - test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 5532fdb3..d5d3a782 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -375,344 +375,6 @@ const TestReader = struct { } }; -test "terminal input preserves fragmented keys queries paste and text after EOF" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ .parts = &.{ - "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", - "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", - } }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.vx.queries_done.load(.unordered)); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var resized = false; - var up = false; - var in_paste = false; - var pasted = false; - var clipboard = false; - var escape = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => |size| { - try std.testing.expect(!resized); - resized = true; - try std.testing.expectEqual(@as(u16, 80), size.cols); - }, - .key_press => |key| { - try std.testing.expect(resized); - if (key.codepoint == vaxis.Key.up) { - up = true; - } else if (key.codepoint == vaxis.Key.escape) { - escape = true; - } else if (key.text) |bytes| { - if (in_paste) try std.testing.expect(up); - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .paste_start => { - try std.testing.expect(up and !in_paste); - in_paste = true; - }, - .paste_end => { - try std.testing.expect(in_paste); - in_paste = false; - pasted = true; - }, - .paste => |bytes| { - defer gpa.free(@constCast(bytes)); - try std.testing.expect(pasted and !in_paste); - try std.testing.expectEqualStrings("clip", bytes); - clipboard = true; - }, - // The device attributes' wake (a capability answer). - .nop => try std.testing.expect(t.vx.queries_done.load(.unordered)), - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); - try std.testing.expect(resized and up and pasted and clipboard and escape); -} - -test "terminal replies and malformed sequences never become typed text" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ - .parts = &.{ - // The startup width queries' answers where the terminal has no - // explicit width: both used to arrive as a bare F3, typed as text. - "a\x1b[1;1R\x1b[1;1R", - // A late report somewhere else on the screen, and DECXCPR. - "\x1b[12;40R\x1b[?3;7;1R", - // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. - "b\x1b\x1b[A", - // A kitty graphics reply cut inside its ST sliced past its input. - "\x1b_Gi=1;OK\x1b", - "\\", - // An X10 mouse report cut after `CSI M` left three bytes as text. - "\x1b[M", - " !!", - // Malformed color and clipboard replies failed the parse, which - // ended input altogether; and a reply ended by BEL ran on to the - // next sequence's ESC, leaving what lay between as text. - "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", - // Device reports whose fields end early. - "\x1b[?1;y\x1b[?997;n\x1b[c", - "\x1b[?62;c", - "c", - }, - }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.vx.queries_done.load(.unordered)); - try std.testing.expect(t.vx.caps.kitty_graphics); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var alt_up = false; - var clicked = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |key| { - if (key.codepoint == vaxis.Key.up and key.mods.alt) { - alt_up = true; - } else if (key.text) |bytes| { - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .mouse => |mouse| { - try std.testing.expectEqual(@as(i16, 0), mouse.col); - clicked = true; - }, - .nop => {}, // the device attributes' wake - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("abc", text.items); - try std.testing.expect(alt_up and clicked); -} - -test "terminal input split at every byte with a gap reads as it does whole" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // Two reads with `gap_ms` between them, as an ssh link delivers a - // sequence cut across two packets (TestReader). - const Events = struct { - /// What the loop was handed, one line per event. - fn of(l: *Loop, out: *std.ArrayList(u8)) !void { - out.clearRetainingCapacity(); - while (try l.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), - .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), - .paste => |bytes| { - try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); - std.testing.allocator.free(@constCast(bytes)); - }, - else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), - }; - } - }; - const Case = struct { bytes: []const u8, kitty: bool = false }; - const cases = [_]Case{ - .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V - .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text - .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own - .{ .bytes = "\x1b[27u", .kitty = true }, // Escape - .{ .bytes = "\x1b[A" }, - .{ .bytes = "\x1bOA" }, - .{ .bytes = "\x1b[3;5~" }, - .{ .bytes = "\x1b\x1b[A" }, - // Four wheel notches: cut at a `;` with 60 ms between the halves, - // ssh's framing lost all four. - .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, - .{ .bytes = "\x1b[200~pasted\x1b[201~" }, - .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, - .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, - .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, - }; - var whole: std.ArrayList(u8) = .empty; - defer whole.deinit(gpa); - var split: std.ArrayList(u8) = .empty; - defer split.deinit(gpa); - for (cases) |case| { - t.vx.caps.kitty_keyboard = case.kitty; - const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); - defer gpa.free(all); - const whole_parts = [_][]const u8{ all, "" }; - var one: TestReader = .{ .parts = &whole_parts }; - try readInput(&t.loop, &one, &t.vx, &t.feed); - try Events.of(&t.loop, &whole); - for (1..all.len) |cut| { - // A cut just after an ESC is the one that has to wait, and a - // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut - // anywhere else is carried however long the gap. - const after_esc = all[cut - 1] == 0x1b; - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&t.loop, &two, &t.vx, &t.feed); - try Events.of(&t.loop, &split); - std.testing.expectEqualStrings(whole.items, split.items) catch |err| { - std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); - return err; - }; - } - } - t.vx.caps.kitty_keyboard = false; -} - -test "an ESC read by itself is the Escape key at once" { - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // More always follows at once: a reader that waited on the ESC would - // take `j` for the rest of its sequence (Alt-j). - for ([_]bool{ false, true }) |kitty| { - t.vx.caps.kitty_keyboard = kitty; - var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!reader.asked); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - const j = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); - try std.testing.expect(!j.mods.alt); - try std.testing.expect(try t.loop.tryEvent() == null); - } - t.vx.caps.kitty_keyboard = false; -} - -test "a frame's answer is taken wherever the reads cut it, and never typed" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - const all = "x" ++ FrameAck.answer ++ "y"; - defer t.feed.ack.waiting.store(false, .release); - for (0..all.len) |cut| { - t.feed.ack.waiting.store(true, .release); - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var reader: TestReader = .{ .parts = &halves }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); - var typed: std.ArrayList(u8) = .empty; - defer typed.deinit(gpa); - var woke = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .nop => woke = true, - .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), - else => return error.UnexpectedInputEvent, - }; - std.testing.expectEqualStrings("xy", typed.items) catch |err| { - std.debug.print("cut at {d}\n", .{cut}); - return err; - }; - try std.testing.expect(woke); - } - // An Escape pressed just before an answer, in the same read, is the - // Escape key, not Alt on the answer. - t.feed.ack.waiting.store(true, .release); - var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&t.loop, &glued, &t.vx, &t.feed); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - try std.testing.expectEqual(@as(u21, 'j'), (try t.loop.tryEvent()).?.key_press.codepoint); - try std.testing.expect(try t.loop.tryEvent() == null); -} - -test "a terminal that never answers a frame stops being asked after one timeout" { - const io = std.testing.io; - var ack: FrameAck = .{}; - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - const t0: u64 = 5 * std.time.ns_per_s; - ack.ask(&out.writer, t0); - try std.testing.expectEqualStrings(FrameAck.request, out.written()); - // Unanswered: the next frame waits, until the timeout. - try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); - try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); - try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); - // Then never again: no request, no wait. - out.clearRetainingCapacity(); - ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); - try std.testing.expectEqual(@as(usize, 0), out.written().len); - try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); -} - -test "terminal input cancellation joins blocked reads and queued EOF" { - const io = std.testing.io; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - const Reader = struct { - file: std.Io.File, - eof: bool, - entered: std.Io.Event = .unset, - release: std.Io.Event = .unset, - returned: std.Io.Event = .unset, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(_: *@This(), _: u32) bool { - return false; - } - fn read(self: *@This(), buf: []u8) !usize { - self.entered.set(std.testing.io); - if (self.eof) { - try self.release.wait(std.testing.io); - self.returned.set(std.testing.io); - return 0; - } - return self.file.readStreaming(std.testing.io, &.{buf}); - } - fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { - inputReader(loop, reader, vx_, feed); - } - }; - const Case = enum { blocked_read, cancel_eof, deliver_eof }; - for (std.enums.values(Case)) |case| { - const eof = case != .blocked_read; - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - defer _ = libc.close(fds[0]); - defer _ = libc.close(fds[1]); - var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; - var loop: Loop = .init(io, undefined, &t.vx); - var feed: Feed = .{}; - var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.vx, &feed }); - defer stopInput(io, &thread); - try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); - try reader.entered.wait(io); - if (eof) { - for (0..512) |_| try loop.postEvent(.nop); - reader.release.set(io); - try reader.returned.wait(io); - } - if (case == .deliver_eof) { - try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); - thread.?.await(io); - } - stopInput(io, &thread); - try std.testing.expect(thread == null); - var count: usize = 0; - while (try loop.tryEvent()) |event| { - const expected: std.meta.Tag(Msg) = if (case == .deliver_eof and count == 511) .quit else .nop; - try std.testing.expectEqual(expected, std.meta.activeTag(event)); - count += 1; - } - try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); - } -} - const PipeTasks = selection_pipe.Tasks; const Pty = struct { @@ -848,179 +510,61 @@ fn kittyPlacement( const aspect_pixel_h: u32 = @intCast( (@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) / geometry.src.w, - ); - declared_rows = @intCast( - (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, - ); - }, - .height => { - declared_rows = safe_rows_u32; - safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( - @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, - ))); - safe_src_h = @min(safe_src_h, geometry.src.h); - const aspect_pixel_w: u32 = @intCast( - (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / - safe_src_h, - ); - declared_cols = @intCast( - (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, - ); - }, - } - if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; - - const src_x = std.math.cast(u16, geometry.src.x) orelse return null; - const src_y = std.math.cast(u16, geometry.src.y) orelse return null; - const src_w = std.math.cast(u16, geometry.src.w) orelse return null; - const src_h = std.math.cast(u16, safe_src_h) orelse return null; - const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; - const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; - if (cell_x >= place.dst.w or cell_y >= place.dst.h) return null; - const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; - const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; - const cell_cols = std.math.cast(u16, @min( - @as(u32, place.dst.w - cell_x), - (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, - )) orelse return null; - const cell_rows = std.math.cast(u16, @min( - @as(u32, place.dst.h - cell_y), - (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, - )) orelse return null; - if (cell_cols == 0 or cell_rows == 0) return null; - - return .{ - .cell_x = cell_x, - .cell_y = cell_y, - .cell_cols = cell_cols, - .cell_rows = cell_rows, - .options = .{ - .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, - .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, - .size = switch (fit) { - .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, - .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, - }, - }, - }; -} - -test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { - var place = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, - .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, - .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, - .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, - .key = pardes.Placement.keyOf(3, 7, 0), - }; - // 10x20 pixel cells: a whole row, one to one. - const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 0), full.cell_x); - try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); - try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); - try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); - try std.testing.expect(full.options.pixel_offset == null); - - // The top of a letterboxed picture: 7 pixels down into the row, 13 - // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns - // only, its source no taller than the 13 pixels left in the row at - // that scale. - place.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; - place.at = .{ .x = 35, .y = 7, .w = 205, .h = 13 }; - const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 3), top.cell_x); - try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); - try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); - try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); - const w = top.options.clip_region.?.width.?; - const h = top.options.clip_region.?.height.?; - try std.testing.expectEqual(@as(u16, 205), w); - try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); - - // Narrower than its cells round to: the source is cut to their scale. - place.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; - place.at = .{ .x = 0, .y = 0, .w = 204, .h = 20 }; - const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); -} - -test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { - // As wide as the body: fit to width. - const base = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, - .src = .{ .w = 96, .h = 10 }, - .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, - .at = .{ .y = 195, .w = 304, .h = 29 }, - .key = pardes.Placement.keyOf(1, 0, 1), - }; - const width = kittyPlacement(base, 80, 16, 640, 256) orelse - return error.MissingSafeKittyWidthFragment; - const width_clip = width.options.clip_region.?; - const width_size = width.options.size.?; - try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); - try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); - try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); - const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + - width_clip.width.? - 1) / width_clip.width.?; - const inferred_rows = (aspect_pixels + 15) / 16; - try std.testing.expect(inferred_rows * 16 <= base.at.?.h); - - // Narrower than the body: fit to height. - var height = base; - height.at.?.w = 300; - height.src.h = 9; - const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse - return error.MissingSafeKittyHeightFragment; - try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); - try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= - height.at.?.h); + ); + declared_rows = @intCast( + (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, + ); + }, + .height => { + declared_rows = safe_rows_u32; + safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( + @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, + ))); + safe_src_h = @min(safe_src_h, geometry.src.h); + const aspect_pixel_w: u32 = @intCast( + (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / + safe_src_h, + ); + declared_cols = @intCast( + (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, + ); + }, + } + if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; - height.at.?.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} + const src_x = std.math.cast(u16, geometry.src.x) orelse return null; + const src_y = std.math.cast(u16, geometry.src.y) orelse return null; + const src_w = std.math.cast(u16, geometry.src.w) orelse return null; + const src_h = std.math.cast(u16, safe_src_h) orelse return null; + const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; + const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; + if (cell_x >= place.dst.w or cell_y >= place.dst.h) return null; + const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; + const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; + const cell_cols = std.math.cast(u16, @min( + @as(u32, place.dst.w - cell_x), + (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, + )) orelse return null; + const cell_rows = std.math.cast(u16, @min( + @as(u32, place.dst.h - cell_y), + (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, + )) orelse return null; + if (cell_cols == 0 or cell_rows == 0) return null; -test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); - const pane = core.panes[0].?; - pane.body.mode = .tty; - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const a = frame.allocator(); - const px = try a.alloc(u8, 64 * 64 * 3); - for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; - const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); - _ = std.base64.standard.Encoder.encode(enc, px); - core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); - while (core.nextEffect()) |_| {} - const s = try core.render(a); - try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); - var art: Art = .{}; - defer art.deinit(gpa); - try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); - const shown = try art.frame(gpa, a, s, false, 16); - const r = core.view().rects[0]; - const x0 = r.x + pardes.config.GUTTER + 7; - const y0 = core.bodyTop(pane, r) + 1; - var painted: usize = 0; - for (0..4) |dy| for (0..8) |dx| { - const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); - const bg = switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => continue, - }; - for (Art.commodore) |c| { - if (std.mem.eql(u8, &c, &bg)) painted += 1; - } + return .{ + .cell_x = cell_x, + .cell_y = cell_y, + .cell_cols = cell_cols, + .cell_rows = cell_rows, + .options = .{ + .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, + .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, + .size = switch (fit) { + .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, + .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, + }, + }, }; - try std.testing.expectEqual(@as(usize, 32), painted); } fn kittyImageRepresentable(place: pardes.Placement) bool { @@ -1284,7 +828,6 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se } } - /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, /// the terminal closed) at the session's start and end, and at a detach and @@ -2458,220 +2001,958 @@ const Shell = struct { tz_render.end(); } - fn postPresent(ctx: ?*anyopaque) void { + fn postPresent(ctx: ?*anyopaque) void { + const s = of(ctx); + if (s.term() != null) s.core.presented(); + tracy.frameMark(); + } + + fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const s = of(ctx); + if (s.adoptions.take(pane)) |a| return s.takeShell(pane, a); + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = s.ptys[pane] != null; + const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { + if (running) return s.core.restartFailed(pane, err); + return s.core.shellFailed(pane, err); + }; + closePty(ctx, pane); // a shell still in the slot goes, reaped + s.gens[pane] +%= 1; + const command = if (s.core.panes[pane]) |pn| pn.command != null else false; + s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + if (s.threads_ok) { + if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + } + } + } + + /// An adopted shell, running already, as pane `pane`'s: told the size + /// twice (a size it never had, then the pane's), which makes it redraw. + fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { + closePty(s, pane); + s.gens[pane] +%= 1; + const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; + s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (s.threads_ok) if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + }; + } + + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + } + + fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| { + const ws = host_io.ptyWinsize(s.core, cols, rows); + _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); + } + } + + fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + const s = of(ctx); + // A command whose exit is recorded is reaped: its group may be + // another's by now. + if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); + } + + /// The pane is gone: hang its pty up, which the kernel passes on to the + /// shell as SIGHUP, and retire the shell. Output still in flight + /// carries the old generation and is dropped. + fn closePty(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + var pt = s.ptys[pane] orelse return; + s.ptys[pane] = null; + s.gens[pane] +%= 1; + pt.reader.cancel(s.io) catch {}; + _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); + } + + fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.ttyTaken(pt.pid, pt.file.handle); + } + + fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { + const s = of(ctx); + const pt = s.ptys[pane] orelse return null; + return host_io.foregroundName(pt.pid, pt.file.handle, buf); + } + + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *@This()) void { + host_io.takeExits(s.core, &s.ptys, s, closeWatched); + } + + fn closeWatched(s: *@This(), id: usize) void { + const pt = &(s.ptys[id] orelse return); + _ = libc.close(pt.file.handle); + s.ptys[id] = null; + } + + fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.file.handle); + } + + fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { + const s = of(ctx); + host_io.writeFile(s.core, &s.watches, pane, path, bytes); + } + + fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { + host_io.writeDump(of(ctx).core, bytes); + } + + fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { + const s = of(ctx); + if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const s = of(ctx); + if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + host_io.dumpThemes(s.core, s.io, s.gpa, pane); + } + + fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { + const s = of(ctx); + // Detached, the session keeps it (a 9P read, a paste here). + const sc = s.term() orelse return s.core.fallback.setClipboard(text); + if (!sc.on) return s.core.fallback.setClipboard(text); + if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; + } + + fn readClipboard(ctx: ?*anyopaque) void { + const s = of(ctx); + const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; + } + + fn openLink(_: ?*anyopaque, url: []const u8) void { + look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly + } + + fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { + const s = of(ctx); + if (!s.threads_ok) { + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); + } + host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); + } + + fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { const s = of(ctx); - if (s.term() != null) s.core.presented(); - tracy.frameMark(); + s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); } - fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + fn pipe(ctx: ?*anyopaque, id: u32) void { const s = of(ctx); - if (s.adoptions.take(pane)) |a| return s.takeShell(pane, a); - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(pane, err); - return s.core.shellFailed(pane, err); - }; - closePty(ctx, pane); // a shell still in the slot goes, reaped - s.gens[pane] +%= 1; - const command = if (s.core.panes[pane]) |pn| pn.command != null else false; - s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - // Only a shell given no directory is asked where it is: one given a - // directory is named by it already (newShell), and asked now, before - // its chdir, it would answer this process's, a rename to undo. - if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - if (s.threads_ok) { - if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - } + if (!s.threads_ok) { + s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); + return s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); } + selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); } - /// An adopted shell, running already, as pane `pane`'s: told the size - /// twice (a size it never had, then the pane's), which makes it redraw. - fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - closePty(s, pane); - s.gens[pane] +%= 1; - const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; - s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); - if (s.threads_ok) if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - }; + fn search(ctx: ?*anyopaque, gen: u32) void { + const s = of(ctx); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); + pardes.Stream.runHere(s.core, gen); } - fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { const s = of(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); + host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { + fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { + of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); + } + }.deliver); } - fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + /// The loop's queue waits for room (a wait the worker's cancel ends). + fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { const s = of(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); - } + s.loop.postEvent(.{ .search_rows = batch }) catch { + batch.deinit(s.gpa); + return false; + }; + return true; } - fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { const s = of(ctx); - // A command whose exit is recorded is reaped: its group may be - // another's by now. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); + var owned = response; + s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); } +}; - /// The pane is gone: hang its pty up, which the kernel passes on to the - /// shell as SIGHUP, and retire the shell. Output still in flight - /// carries the old generation and is dropped. - fn closePty(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - var pt = s.ptys[pane] orelse return; - s.ptys[pane] = null; - s.gens[pane] +%= 1; - pt.reader.cancel(s.io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); +fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { + const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); + const copy = s.lsp_gpa.dupe(u8, text) catch return; + const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; + if (!posted) s.lsp_gpa.free(copy); +} + +fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { + while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; + return; + } + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [4096]u8 = undefined; + while (true) { + const n = file.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + loop.postEvent(.files_changed) catch break; + } +} + +fn keepSignal(_: posix.SIG) callconv(.c) void {} + +/// A replica client's (`remote`): a hangup is its end, whoever sent it. +var hangup_quits = false; + +fn winchWatch(loop: *Loop) void { + var set = posix.sigemptyset(); + posix.sigaddset(&set, posix.SIG.WINCH); + if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); + while (true) { + var sig: c_int = 0; + if (libc.sigwait(&set, &sig) != 0) continue; + // The terminals are the loop's: it asks each its size, and takes a + // hangup as the end of the one that hung up. + const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; + loop.postEvent(ev) catch {}; + } +} + +/// A wait with a timeout: post one `.wake` when it runs out. The wake joins +/// the input queue, so a key or a click that lands first is handled at once +/// instead of after a blind sleep; vaxis's queue has no timed wait. Each +/// request bumps `wake_gen`, which cuts short a sleep still timing an +/// earlier, longer request (an 800 ms linger interrupted by a key that +/// starts a 16 ms fall) and times the new one instead. +var wake_gen: std.atomic.Value(u32) = .init(0); +var wake_ms: std.atomic.Value(u32) = .init(0); + +fn requestWake(io: std.Io, ms: u32) void { + wake_ms.store(ms, .release); + _ = wake_gen.fetchAdd(1, .acq_rel); + io.futexWake(u32, &wake_gen.raw, 1); +} + +fn wakeWatch(io: std.Io, loop: *Loop) void { + var seen = wake_gen.load(.acquire); + while (true) { + // Asleep until a request. + while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); + seen = wake_gen.load(.acquire); + if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; + } +} + +/// Sleep out the latest request; true when it ran its course, false when +/// none is pending. A newer request met on the way restarts the timing. +fn timeWake(io: std.Io, seen: *u32) bool { + while (true) { + const ms = wake_ms.load(.acquire); + const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; + while (true) { + const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + if (now >= deadline) return true; + io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ + .raw = .fromNanoseconds(@intCast(deadline - now)), + .clock = .awake, + } }) catch {}; + const gen = wake_gen.load(.acquire); + if (gen != seen.*) { + seen.* = gen; + break; + } + } + } +} + +fn wakeFs(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + _ = loop.tryPostEvent(.fs_ready) catch {}; +} + +/// Each pane's reads posted and not yet taken in. Two at most: a flood the +/// loop cannot keep up with waits in its pty, not in the queue ahead of a +/// key and its echo (hundreds of 4 KB reads queued were half a second). +var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); + +/// A read of pane `id` taken in (or dropped): its reader may read on. Never +/// below zero, for an event no reader posted (a test's). +fn tookRead(io: std.Io, id: usize) void { + var queued = reads_queued[id].load(.acquire); + while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { + if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); + return; + }; +} + +fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; + read: while (true) { + while (true) { + const queued = reads_queued[id].load(.acquire); + if (queued < 2) break; + io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; + } + const n = pty.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + const bytes = try gpa.dupe(u8, buf[0..n]); + _ = reads_queued[id].fetchAdd(1, .acq_rel); + loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { + tookRead(io, id); + gpa.free(bytes); + break; + }; } + _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; +} + +const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; + +fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { + const button: pardes.Mouse.Button = switch (m.button) { + .left => .left, + .middle => .middle, + .right => .right, + .wheel_up => .wheel_up, + .wheel_down => .wheel_down, + .wheel_left => .wheel_left, + .wheel_right => .wheel_right, + // A mouse's side buttons, as xterm reports them: Back and Forward. + .button_8 => .back, + .button_9 => .forward, + .none => .none, // button-less motion: hover tracking + else => return null, + }; + return .{ .mouse = .{ + .button = button, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + .col = cellOf(m.col), + .row = cellOf(m.row), + .ctrl = m.mods.ctrl, + .shift = m.mods.shift, + .alt = m.mods.alt, + } }; +} - fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.file.handle); - } +/// A report's cell, 0-based: one before the first (SGR's 0, a drag past +/// the window's top or left edge, in cells or in 1016's pixels) is the +/// first, never a panic; past the far edge the core clamps it. +pub fn cellOf(v: i16) u16 { + return @intCast(@max(0, v)); +} - fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { - const s = of(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.file.handle, buf); - } +/// A replica client's own line over its frame's last row (`Remote.notify`), +/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps +/// the slices). +fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { + if (rows == 0) return; + for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ + .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, + .style = .{ .reverse = true }, + }); +} - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *@This()) void { - host_io.takeExits(s.core, &s.ptys, s, closeWatched); +/// A blank whose ink alone changed is not sent: vaxis's render skips it +/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows +/// nowhere. Deciding that here cost every cell of every frame a look at the +/// frame before; vaxis already makes that comparison. +/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind +/// the cursor in its body, on the page's own ground, that ground drawn +/// toward the text's colour; a copy of `shown` while it fades. +fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { + var at: [5]JumpTrail.Cell = undefined; + const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); + if (lit.len == 0) return shown; + const cursor = shown.cursor.?; + const body = for (shown.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 shown; + const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; + const page = shown.chrome.page orelse pardes.colors.null_page; + const out = try arena.create(pardes.Surface); + out.* = shown.*; + out.cells = try arena.dupe(pardes.Cell, shown.cells); + 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 c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; + // On the page's own ground alone: never a selection or a match. + const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (!std.mem.eql(u8, &ground, &page)) continue; + if (c.default) c.style = .{}; + c.default = false; + c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; } + return out; +} - fn closeWatched(s: *@This(), id: usize) void { - const pt = &(s.ptys[id] orelse return); - _ = libc.close(pt.file.handle); - s.ptys[id] = null; - } +/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does +/// not answer vaxis's query. +fn colortermTruecolor() bool { + const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); + return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); +} - fn killJob(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.file.handle); +/// The tty's picture of the glide (glide.zig, anim 12): the body's rows +/// moved by the offset rounded to whole rows (the position rounded, never +/// the step, so a slowing glide's steps come further apart), the rows that +/// left in the gap it opens, and a caret whose line rode the scroll carried +/// with it; `canonical` itself while the picture is where the core is, else +/// a copy of it in `arena`. The rows are walked from the side they move +/// toward, so each is read before a move writes over it. +fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { + const k: i32 = @intFromFloat(@round(glide.follow.offset)); + const w = glide.bw(); + const h = glide.body_h; + const x0 = glide.rect.x + pardes.config.GUTTER; + const y0 = glide.body_y; + if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; + const out = try arena.create(pardes.Surface); + out.* = canonical.*; + out.cells = try arena.dupe(pardes.Cell, canonical.cells); + const cols: usize = out.cols; + for (0..h) |i| { + const r = if (k > 0) i else h - 1 - i; + const from = @as(i32, @intCast(r)) + k; + const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; + const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) + out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] + else if (from < 0 and -from - 1 < glide.nabove) + glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] + else if (from >= h and from - h < glide.nbelow) + glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] + else + null; + if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); } + if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { + const y = @as(i32, c.y) - k; + if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; + }; + return out; +} - fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { - const s = of(ctx); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); +fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { + win.clear(); + var y: u16 = 0; + while (y < rows) : (y += 1) { + var x: u16 = 0; + while (x < cols) : (x += 1) { + const cell = &cells[@as(usize, y) * cols + x]; + if (cell.default) continue; + win.writeCell(x, y, .{ + .char = .{ .grapheme = cell.grapheme() }, + .style = vaxis_input.style(cell.style), + }); + } } +} - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(of(ctx).core, bytes); - } +test "terminal input preserves fragmented keys queries paste and text after EOF" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ .parts = &.{ + "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", + "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", + } }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.vx.queries_done.load(.unordered)); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var resized = false; + var up = false; + var in_paste = false; + var pasted = false; + var clipboard = false; + var escape = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => |size| { + try std.testing.expect(!resized); + resized = true; + try std.testing.expectEqual(@as(u16, 80), size.cols); + }, + .key_press => |key| { + try std.testing.expect(resized); + if (key.codepoint == vaxis.Key.up) { + up = true; + } else if (key.codepoint == vaxis.Key.escape) { + escape = true; + } else if (key.text) |bytes| { + if (in_paste) try std.testing.expect(up); + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .paste_start => { + try std.testing.expect(up and !in_paste); + in_paste = true; + }, + .paste_end => { + try std.testing.expect(in_paste); + in_paste = false; + pasted = true; + }, + .paste => |bytes| { + defer gpa.free(@constCast(bytes)); + try std.testing.expect(pasted and !in_paste); + try std.testing.expectEqualStrings("clip", bytes); + clipboard = true; + }, + // The device attributes' wake (a capability answer). + .nop => try std.testing.expect(t.vx.queries_done.load(.unordered)), + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); + try std.testing.expect(resized and up and pasted and clipboard and escape); +} + +test "terminal replies and malformed sequences never become typed text" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ + .parts = &.{ + // The startup width queries' answers where the terminal has no + // explicit width: both used to arrive as a bare F3, typed as text. + "a\x1b[1;1R\x1b[1;1R", + // A late report somewhere else on the screen, and DECXCPR. + "\x1b[12;40R\x1b[?3;7;1R", + // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. + "b\x1b\x1b[A", + // A kitty graphics reply cut inside its ST sliced past its input. + "\x1b_Gi=1;OK\x1b", + "\\", + // An X10 mouse report cut after `CSI M` left three bytes as text. + "\x1b[M", + " !!", + // Malformed color and clipboard replies failed the parse, which + // ended input altogether; and a reply ended by BEL ran on to the + // next sequence's ESC, leaving what lay between as text. + "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", + // Device reports whose fields end early. + "\x1b[?1;y\x1b[?997;n\x1b[c", + "\x1b[?62;c", + "c", + }, + }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.vx.queries_done.load(.unordered)); + try std.testing.expect(t.vx.caps.kitty_graphics); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var alt_up = false; + var clicked = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |key| { + if (key.codepoint == vaxis.Key.up and key.mods.alt) { + alt_up = true; + } else if (key.text) |bytes| { + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .mouse => |mouse| { + try std.testing.expectEqual(@as(i16, 0), mouse.col); + clicked = true; + }, + .nop => {}, // the device attributes' wake + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("abc", text.items); + try std.testing.expect(alt_up and clicked); +} - fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) - s.loop.postEvent(.files_changed) catch {}; +test "terminal input split at every byte with a gap reads as it does whole" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // Two reads with `gap_ms` between them, as an ssh link delivers a + // sequence cut across two packets (TestReader). + const Events = struct { + /// What the loop was handed, one line per event. + fn of(l: *Loop, out: *std.ArrayList(u8)) !void { + out.clearRetainingCapacity(); + while (try l.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), + .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), + .paste => |bytes| { + try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); + std.testing.allocator.free(@constCast(bytes)); + }, + else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), + }; + } + }; + const Case = struct { bytes: []const u8, kitty: bool = false }; + const cases = [_]Case{ + .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V + .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text + .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own + .{ .bytes = "\x1b[27u", .kitty = true }, // Escape + .{ .bytes = "\x1b[A" }, + .{ .bytes = "\x1bOA" }, + .{ .bytes = "\x1b[3;5~" }, + .{ .bytes = "\x1b\x1b[A" }, + // Four wheel notches: cut at a `;` with 60 ms between the halves, + // ssh's framing lost all four. + .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, + .{ .bytes = "\x1b[200~pasted\x1b[201~" }, + .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, + .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, + .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, + }; + var whole: std.ArrayList(u8) = .empty; + defer whole.deinit(gpa); + var split: std.ArrayList(u8) = .empty; + defer split.deinit(gpa); + for (cases) |case| { + t.vx.caps.kitty_keyboard = case.kitty; + const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); + defer gpa.free(all); + const whole_parts = [_][]const u8{ all, "" }; + var one: TestReader = .{ .parts = &whole_parts }; + try readInput(&t.loop, &one, &t.vx, &t.feed); + try Events.of(&t.loop, &whole); + for (1..all.len) |cut| { + // A cut just after an ESC is the one that has to wait, and a + // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut + // anywhere else is carried however long the gap. + const after_esc = all[cut - 1] == 0x1b; + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; + try readInput(&t.loop, &two, &t.vx, &t.feed); + try Events.of(&t.loop, &split); + std.testing.expectEqualStrings(whole.items, split.items) catch |err| { + std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); + return err; + }; + } } + t.vx.caps.kitty_keyboard = false; +} - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) - s.loop.postEvent(.files_changed) catch {}; +test "an ESC read by itself is the Escape key at once" { + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // More always follows at once: a reader that waited on the ESC would + // take `j` for the rest of its sequence (Alt-j). + for ([_]bool{ false, true }) |kitty| { + t.vx.caps.kitty_keyboard = kitty; + var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!reader.asked); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + const j = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); + try std.testing.expect(!j.mods.alt); + try std.testing.expect(try t.loop.tryEvent() == null); } + t.vx.caps.kitty_keyboard = false; +} - fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); +test "a frame's answer is taken wherever the reads cut it, and never typed" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const all = "x" ++ FrameAck.answer ++ "y"; + defer t.feed.ack.waiting.store(false, .release); + for (0..all.len) |cut| { + t.feed.ack.waiting.store(true, .release); + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var reader: TestReader = .{ .parts = &halves }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); + var typed: std.ArrayList(u8) = .empty; + defer typed.deinit(gpa); + var woke = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .nop => woke = true, + .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), + else => return error.UnexpectedInputEvent, + }; + std.testing.expectEqualStrings("xy", typed.items) catch |err| { + std.debug.print("cut at {d}\n", .{cut}); + return err; + }; + try std.testing.expect(woke); } + // An Escape pressed just before an answer, in the same read, is the + // Escape key, not Alt on the answer. + t.feed.ack.waiting.store(true, .release); + var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; + try readInput(&t.loop, &glued, &t.vx, &t.feed); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + try std.testing.expectEqual(@as(u21, 'j'), (try t.loop.tryEvent()).?.key_press.codepoint); + try std.testing.expect(try t.loop.tryEvent() == null); +} - fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - const s = of(ctx); - // Detached, the session keeps it (a 9P read, a paste here). - const sc = s.term() orelse return s.core.fallback.setClipboard(text); - if (!sc.on) return s.core.fallback.setClipboard(text); - if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; - } +test "a terminal that never answers a frame stops being asked after one timeout" { + const io = std.testing.io; + var ack: FrameAck = .{}; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + const t0: u64 = 5 * std.time.ns_per_s; + ack.ask(&out.writer, t0); + try std.testing.expectEqualStrings(FrameAck.request, out.written()); + // Unanswered: the next frame waits, until the timeout. + try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); + try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); + try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); + // Then never again: no request, no wait. + out.clearRetainingCapacity(); + ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); + try std.testing.expectEqual(@as(usize, 0), out.written().len); + try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); +} - fn readClipboard(ctx: ?*anyopaque) void { - const s = of(ctx); - const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; +test "terminal input cancellation joins blocked reads and queued EOF" { + const io = std.testing.io; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const Reader = struct { + file: std.Io.File, + eof: bool, + entered: std.Io.Event = .unset, + release: std.Io.Event = .unset, + returned: std.Io.Event = .unset, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(_: *@This(), _: u32) bool { + return false; + } + fn read(self: *@This(), buf: []u8) !usize { + self.entered.set(std.testing.io); + if (self.eof) { + try self.release.wait(std.testing.io); + self.returned.set(std.testing.io); + return 0; + } + return self.file.readStreaming(std.testing.io, &.{buf}); + } + fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { + inputReader(loop, reader, vx_, feed); + } + }; + const Case = enum { blocked_read, cancel_eof, deliver_eof }; + for (std.enums.values(Case)) |case| { + const eof = case != .blocked_read; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + defer _ = libc.close(fds[0]); + defer _ = libc.close(fds[1]); + var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; + var loop: Loop = .init(io, undefined, &t.vx); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.vx, &feed }); + defer stopInput(io, &thread); + try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); + try reader.entered.wait(io); + if (eof) { + for (0..512) |_| try loop.postEvent(.nop); + reader.release.set(io); + try reader.returned.wait(io); + } + if (case == .deliver_eof) { + try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); + thread.?.await(io); + } + stopInput(io, &thread); + try std.testing.expect(thread == null); + var count: usize = 0; + while (try loop.tryEvent()) |event| { + const expected: std.meta.Tag(Msg) = if (case == .deliver_eof and count == 511) .quit else .nop; + try std.testing.expectEqual(expected, std.meta.activeTag(event)); + count += 1; + } + try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); } +} - fn openLink(_: ?*anyopaque, url: []const u8) void { - look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly - } +test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { + var place = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, + .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, + .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, + .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, + .key = pardes.Placement.keyOf(3, 7, 0), + }; + // 10x20 pixel cells: a whole row, one to one. + const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 0), full.cell_x); + try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); + try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); + try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); + try std.testing.expect(full.options.pixel_offset == null); - fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); - } - host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); - } + // The top of a letterboxed picture: 7 pixels down into the row, 13 + // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns + // only, its source no taller than the 13 pixels left in the row at + // that scale. + place.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; + place.at = .{ .x = 35, .y = 7, .w = 205, .h = 13 }; + const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 3), top.cell_x); + try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); + try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); + try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); + const w = top.options.clip_region.?.width.?; + const h = top.options.clip_region.?.height.?; + try std.testing.expectEqual(@as(u16, 205), w); + try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const s = of(ctx); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); - } + // Narrower than its cells round to: the source is cut to their scale. + place.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; + place.at = .{ .x = 0, .y = 0, .w = 204, .h = 20 }; + const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); +} - fn pipe(ctx: ?*anyopaque, id: u32) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); - } - selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); - } +test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { + // As wide as the body: fit to width. + const base = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, + .src = .{ .w = 96, .h = 10 }, + .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, + .at = .{ .y = 195, .w = 304, .h = 29 }, + .key = pardes.Placement.keyOf(1, 0, 1), + }; + const width = kittyPlacement(base, 80, 16, 640, 256) orelse + return error.MissingSafeKittyWidthFragment; + const width_clip = width.options.clip_region.?; + const width_size = width.options.size.?; + try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); + try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); + try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); + const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + + width_clip.width.? - 1) / width_clip.width.?; + const inferred_rows = (aspect_pixels + 15) / 16; + try std.testing.expect(inferred_rows * 16 <= base.at.?.h); - fn search(ctx: ?*anyopaque, gen: u32) void { - const s = of(ctx); - if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); - pardes.Stream.runHere(s.core, gen); - } + // Narrower than the body: fit to height. + var height = base; + height.at.?.w = 300; + height.src.h = 9; + const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse + return error.MissingSafeKittyHeightFragment; + try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); + try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= + height.at.?.h); - fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { - const s = of(ctx); - if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); - host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { - fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); - } - }.deliver); - } + height.at.?.h = 13; + try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); +} - /// The loop's queue waits for room (a wait the worker's cancel ends). - fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { - const s = of(ctx); - s.loop.postEvent(.{ .search_rows = batch }) catch { - batch.deinit(s.gpa); - return false; +test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); + const pane = core.panes[0].?; + pane.body.mode = .tty; + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const a = frame.allocator(); + const px = try a.alloc(u8, 64 * 64 * 3); + for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; + const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); + _ = std.base64.standard.Encoder.encode(enc, px); + core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); + while (core.nextEffect()) |_| {} + const s = try core.render(a); + try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); + var art: Art = .{}; + defer art.deinit(gpa); + try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); + const shown = try art.frame(gpa, a, s, false, 16); + const r = core.view().rects[0]; + const x0 = r.x + pardes.config.GUTTER + 7; + const y0 = core.bodyTop(pane, r) + 1; + var painted: usize = 0; + for (0..4) |dy| for (0..8) |dx| { + const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); + const bg = switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => continue, }; - return true; - } - - fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { - const s = of(ctx); - var owned = response; - s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); - } -}; + for (Art.commodore) |c| { + if (std.mem.eql(u8, &c, &bg)) painted += 1; + } + }; + try std.testing.expectEqual(@as(usize, 32), painted); +} test "TTY queued results reject old PTY generations and LSP request IDs" { const gpa = std.testing.allocator; @@ -2712,140 +2993,51 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { test "TTY 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 shell: Shell = .{ - .io = failing_io, - .gpa = failing.allocator(), - .lsp_gpa = failing.allocator(), - .core = core, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - .threads_ok = true, - }; - 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 = "", - }; - Shell.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; - Shell.pipe(&shell, pipe_id); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); - } -} - -fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { - const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); - const copy = s.lsp_gpa.dupe(u8, text) catch return; - const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; - if (!posted) s.lsp_gpa.free(copy); -} - -fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { - while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; - return; - } - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [4096]u8 = undefined; - while (true) { - const n = file.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - loop.postEvent(.files_changed) catch break; - } -} - -fn keepSignal(_: posix.SIG) callconv(.c) void {} - -/// A replica client's (`remote`): a hangup is its end, whoever sent it. -var hangup_quits = false; - -fn winchWatch(loop: *Loop) void { - var set = posix.sigemptyset(); - posix.sigaddset(&set, posix.SIG.WINCH); - if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); - while (true) { - var sig: c_int = 0; - if (libc.sigwait(&set, &sig) != 0) continue; - // The terminals are the loop's: it asks each its size, and takes a - // hangup as the end of the one that hung up. - const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; - loop.postEvent(ev) catch {}; - } -} - -/// A wait with a timeout: post one `.wake` when it runs out. The wake joins -/// the input queue, so a key or a click that lands first is handled at once -/// instead of after a blind sleep; vaxis's queue has no timed wait. Each -/// request bumps `wake_gen`, which cuts short a sleep still timing an -/// earlier, longer request (an 800 ms linger interrupted by a key that -/// starts a 16 ms fall) and times the new one instead. -var wake_gen: std.atomic.Value(u32) = .init(0); -var wake_ms: std.atomic.Value(u32) = .init(0); - -fn requestWake(io: std.Io, ms: u32) void { - wake_ms.store(ms, .release); - _ = wake_gen.fetchAdd(1, .acq_rel); - io.futexWake(u32, &wake_gen.raw, 1); -} - -fn wakeWatch(io: std.Io, loop: *Loop) void { - var seen = wake_gen.load(.acquire); - while (true) { - // Asleep until a request. - while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); - seen = wake_gen.load(.acquire); - if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; - } -} + 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 shell: Shell = .{ + .io = failing_io, + .gpa = failing.allocator(), + .lsp_gpa = failing.allocator(), + .core = core, + .prompt_rcs = undefined, + .loop = undefined, + .frame = undefined, + .paste_buf = undefined, + .inotify_fd = -1, + .threads_ok = true, + }; + 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 = "", + }; + Shell.lsp(&shell, req); + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); -/// Sleep out the latest request; true when it ran its course, false when -/// none is pending. A newer request met on the way restarts the timing. -fn timeWake(io: std.Io, seen: *u32) bool { - while (true) { - const ms = wake_ms.load(.acquire); - const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; - while (true) { - const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - if (now >= deadline) return true; - io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ - .raw = .fromNanoseconds(@intCast(deadline - now)), - .clock = .awake, - } }) catch {}; - const gen = wake_gen.load(.acquire); - if (gen != seen.*) { - seen.* = gen; - break; - } - } + 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; + Shell.pipe(&shell, pipe_id); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(shell.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); } } @@ -2872,51 +3064,6 @@ test "a short wake request cuts short a long one still sleeping" { try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms); } -fn wakeFs(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - _ = loop.tryPostEvent(.fs_ready) catch {}; -} - -/// Each pane's reads posted and not yet taken in. Two at most: a flood the -/// loop cannot keep up with waits in its pty, not in the queue ahead of a -/// key and its echo (hundreds of 4 KB reads queued were half a second). -var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); - -/// A read of pane `id` taken in (or dropped): its reader may read on. Never -/// below zero, for an event no reader posted (a test's). -fn tookRead(io: std.Io, id: usize) void { - var queued = reads_queued[id].load(.acquire); - while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { - if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); - return; - }; -} - -fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [0x10000]u8 = undefined; - read: while (true) { - while (true) { - const queued = reads_queued[id].load(.acquire); - if (queued < 2) break; - io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; - } - const n = pty.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - const bytes = try gpa.dupe(u8, buf[0..n]); - _ = reads_queued[id].fetchAdd(1, .acq_rel); - loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { - tookRead(io, id); - gpa.free(bytes); - break; - }; - } - _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; -} - -const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; - test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { const gpa = std.testing.allocator; var t: TestInput = undefined; @@ -3023,44 +3170,6 @@ test "keypad Enter matches Return for editor input terminal writes and paste" { } } -fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { - const button: pardes.Mouse.Button = switch (m.button) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .wheel_up, - .wheel_down => .wheel_down, - .wheel_left => .wheel_left, - .wheel_right => .wheel_right, - // A mouse's side buttons, as xterm reports them: Back and Forward. - .button_8 => .back, - .button_9 => .forward, - .none => .none, // button-less motion: hover tracking - else => return null, - }; - return .{ .mouse = .{ - .button = button, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - .col = cellOf(m.col), - .row = cellOf(m.row), - .ctrl = m.mods.ctrl, - .shift = m.mods.shift, - .alt = m.mods.alt, - } }; -} - -/// A report's cell, 0-based: one before the first (SGR's 0, a drag past -/// the window's top or left edge, in cells or in 1016's pixels) is the -/// first, never a panic; past the far edge the core clamps it. -pub fn cellOf(v: i16) u16 { - return @intCast(@max(0, v)); -} - test "a mouse report at row or column 0, or before it, is the window's edge, never a panic" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -3081,54 +3190,6 @@ test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 } } -/// A replica client's own line over its frame's last row (`Remote.notify`), -/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps -/// the slices). -fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { - if (rows == 0) return; - for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ - .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, - .style = .{ .reverse = true }, - }); -} - -/// A blank whose ink alone changed is not sent: vaxis's render skips it -/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows -/// nowhere. Deciding that here cost every cell of every frame a look at the -/// frame before; vaxis already makes that comparison. -/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind -/// the cursor in its body, on the page's own ground, that ground drawn -/// toward the text's colour; a copy of `shown` while it fades. -fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { - var at: [5]JumpTrail.Cell = undefined; - const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return shown; - const cursor = shown.cursor.?; - const body = for (shown.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 shown; - const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; - const page = shown.chrome.page orelse pardes.colors.null_page; - const out = try arena.create(pardes.Surface); - out.* = shown.*; - out.cells = try arena.dupe(pardes.Cell, shown.cells); - 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 c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - if (c.default) c.style = .{}; - c.default = false; - c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; - } - return out; -} - test "a jump's trail tints the ground behind the cursor in its body, and is gone by 120 ms" { std.testing.refAllDecls(JumpTrail); const gpa = std.testing.allocator; @@ -3164,68 +3225,6 @@ test "a jump's trail tints the ground behind the cursor in its body, and is gone try std.testing.expect(!trail.active); } -/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does -/// not answer vaxis's query. -fn colortermTruecolor() bool { - const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); - return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); -} - -/// The tty's picture of the glide (glide.zig, anim 12): the body's rows -/// moved by the offset rounded to whole rows (the position rounded, never -/// the step, so a slowing glide's steps come further apart), the rows that -/// left in the gap it opens, and a caret whose line rode the scroll carried -/// with it; `canonical` itself while the picture is where the core is, else -/// a copy of it in `arena`. The rows are walked from the side they move -/// toward, so each is read before a move writes over it. -fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { - const k: i32 = @intFromFloat(@round(glide.follow.offset)); - const w = glide.bw(); - const h = glide.body_h; - const x0 = glide.rect.x + pardes.config.GUTTER; - const y0 = glide.body_y; - if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; - const out = try arena.create(pardes.Surface); - out.* = canonical.*; - out.cells = try arena.dupe(pardes.Cell, canonical.cells); - const cols: usize = out.cols; - for (0..h) |i| { - const r = if (k > 0) i else h - 1 - i; - const from = @as(i32, @intCast(r)) + k; - const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; - const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) - out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] - else if (from < 0 and -from - 1 < glide.nabove) - glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] - else if (from >= h and from - h < glide.nbelow) - glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] - else - null; - if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); - } - if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { - const y = @as(i32, c.y) - k; - if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; - }; - return out; -} - -fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { - win.clear(); - var y: u16 = 0; - while (y < rows) : (y += 1) { - var x: u16 = 0; - while (x < cols) : (x += 1) { - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default) continue; - win.writeCell(x, y, .{ - .char = .{ .grapheme = cell.grapheme() }, - .style = vaxis_input.style(cell.style), - }); - } - } -} - test "a fade sends the text it dims, not the blanks beside it" { const gpa = std.testing.allocator; var t: TestInput = undefined; diff --git a/src/walk.zig b/src/walk.zig index d7ee63b3..3641d327 100644 --- a/src/walk.zig +++ b/src/walk.zig @@ -528,80 +528,6 @@ fn decodeError(comptime E: type, r: *Reader, out: *E) TapeError!void { out.* = errorNamed(E, try r.take(len)) orelse return error.NoSuchError; } -test "a value comes back from its bytes" { - const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 }; - var buf: [256]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } }; - for (&values) |*v| try encode(E, v, &w); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var r: Reader = .{ .bytes = w.buffered() }; - for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator()))); - try std.testing.expectEqual(r.bytes.len, r.at); -} - -test "an error is taped by its name, which another build reads back as its own" { - // The build's number for an error is its own: 451 of 505 names were - // numbered otherwise in a Linux window's build than a terminal's, so a - // window replica read a terminal session's FileNotFound as another. - var buf: [64]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir; - try encode(@TypeOf(failed), &failed, &w); - try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered()); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var r: Reader = .{ .bytes = w.buffered() }; - try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator())); - // A name this build's set lacks (an OS's own): the tape is another - // build's, and the replay diverges rather than read some other error. - r = .{ .bytes = "\x00\x0c\x00FileTooLarge" }; - try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator())); - // An anyerror (a host's report) is read back as one of tape.Failure's. - const Report = struct { err: anyerror }; - w = .fixed(&buf); - try encode(Report, &.{ .err = error.FileNotFound }, &w); - r = .{ .bytes = w.buffered() }; - try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err); -} - -test "an enum is digested by its name, which another build may number otherwise" { - // registry.Builtin as a Linux build makes it (Tty9p in it) and as a - // FreeBSD one does: LocationsConfig is another number in each. - const Linux = enum { Look, Tty9p, LocationsConfig }; - const FreeBSD = enum { Look, LocationsConfig }; - const S = struct { from: Linux, also: [2]Linux }; - const T = struct { from: FreeBSD, also: [2]FreeBSD }; - try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } })); - try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } })); -} - -test "a digest is of values: the same text at two addresses is one digest" { - const S = struct { name: []const u8, n: u32, next: ?*const u32 }; - const a = "same text"; - var b: [9]u8 = undefined; - @memcpy(&b, a); - const x: u32 = 7; - const y: u32 = 7; - try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y })); - try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x })); -} - -test "an annotated field is in no digest, and a length cuts its array" { - const S = struct { - kept: u32, - cache: u32, - ring: [4]u8, - ring_len: u8, - pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} }; - }; - try std.testing.expectEqual( - digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }), - digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }), - ); -} - // ---- the dump: the same walk, by name, for another build ---- // // A dump (docs/next-daemon.md, phase 2) is `dump_magic`, then a table of @@ -800,7 +726,7 @@ fn writeTable(comptime types: []const type, w: *std.Io.Writer) !void { try writeU32(w, types.len); inline for (types) |T| { const k = comptime kindOf(T); - try w.writeByte(@intFromEnum(k)); + try w.writeByte(@backingInt(k)); switch (k) { .int => { try w.writeByte(@intFromBool(@typeInfo(T).int.signedness == .signed)); @@ -962,7 +888,7 @@ pub fn Dump(comptime roots: []const type) type { .bool => try w.writeByte(@intFromBool(v.*)), .int => try putInt(T, v.*, w), .float => try w.writeAll(std.mem.asBytes(v)), - .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @intFromEnum(v.*), w), + .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @backingInt(v.*), w), .optional => if (v.*) |*payload| { try w.writeByte(1); try d.value(@typeInfo(T).optional.child, payload); @@ -1306,7 +1232,7 @@ pub fn Load(comptime roots: []const type) type { .@"enum" => { const e = @typeInfo(T).@"enum"; if (l.same) { - out.* = @enumFromInt(try l.readInt(e.tag_type, s)); + out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s))); return; } const n = try l.readInt(i128, s); @@ -1319,7 +1245,7 @@ pub fn Load(comptime roots: []const type) type { }; if (e.mode == .nonexhaustive and was == null) if (std.math.cast(e.tag_type, n)) |tag| { - out.* = @enumFromInt(tag); + out.* = @fromBackingInt(@intCast(tag)); return; }; l.note("{s}: no {s} here", .{ l.field, was orelse "such value" }); @@ -1752,7 +1678,7 @@ pub const Put = struct { .float => try c.write(.{ .float = v.* }), .@"enum" => if (std.enums.tagName(T, v.*)) |name| { try c.write(.{ .bytes = name }); - } else try c.write(.{ .int = @intCast(@intFromEnum(v.*)) }), + } else try c.write(.{ .int = @intCast(@backingInt(v.*)) }), .optional => { const C = @typeInfo(T).optional.child; if (v.*) |*payload| { @@ -2047,7 +1973,7 @@ pub const Get = struct { }, .int, .uint => if (e.mode == .nonexhaustive) { const n: i64 = @bitCast(slot.value); - out.* = @enumFromInt(std.math.cast(e.tag_type, n) orelse return error.Incompatible); + out.* = @fromBackingInt(@intCast(std.math.cast(e.tag_type, n) orelse return error.Incompatible)); } else return error.Incompatible, else => return error.Incompatible, } @@ -2404,6 +2330,80 @@ pub const Get = struct { } }; +test "a value comes back from its bytes" { + const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 }; + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } }; + for (&values) |*v| try encode(E, v, &w); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var r: Reader = .{ .bytes = w.buffered() }; + for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator()))); + try std.testing.expectEqual(r.bytes.len, r.at); +} + +test "an error is taped by its name, which another build reads back as its own" { + // The build's number for an error is its own: 451 of 505 names were + // numbered otherwise in a Linux window's build than a terminal's, so a + // window replica read a terminal session's FileNotFound as another. + var buf: [64]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir; + try encode(@TypeOf(failed), &failed, &w); + try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered()); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var r: Reader = .{ .bytes = w.buffered() }; + try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator())); + // A name this build's set lacks (an OS's own): the tape is another + // build's, and the replay diverges rather than read some other error. + r = .{ .bytes = "\x00\x0c\x00FileTooLarge" }; + try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator())); + // An anyerror (a host's report) is read back as one of tape.Failure's. + const Report = struct { err: anyerror }; + w = .fixed(&buf); + try encode(Report, &.{ .err = error.FileNotFound }, &w); + r = .{ .bytes = w.buffered() }; + try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err); +} + +test "an enum is digested by its name, which another build may number otherwise" { + // registry.Builtin as a Linux build makes it (Tty9p in it) and as a + // FreeBSD one does: LocationsConfig is another number in each. + const Linux = enum { Look, Tty9p, LocationsConfig }; + const FreeBSD = enum { Look, LocationsConfig }; + const S = struct { from: Linux, also: [2]Linux }; + const T = struct { from: FreeBSD, also: [2]FreeBSD }; + try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } })); + try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } })); +} + +test "a digest is of values: the same text at two addresses is one digest" { + const S = struct { name: []const u8, n: u32, next: ?*const u32 }; + const a = "same text"; + var b: [9]u8 = undefined; + @memcpy(&b, a); + const x: u32 = 7; + const y: u32 = 7; + try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y })); + try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x })); +} + +test "an annotated field is in no digest, and a length cuts its array" { + const S = struct { + kept: u32, + cache: u32, + ring: [4]u8, + ring_len: u8, + pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} }; + }; + try std.testing.expectEqual( + digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }), + digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }), + ); +} + test "an optional slice comes back, and the fields after it" { const S = struct { before: u32 = 0, command: ?[]u8 = null, after: u32 = 0 }; var text = "sleep 30".*; -- cgit v1.3